0

我想不通。它可以在一个简单的测试工作簿中使用,但是当我尝试在更大的工作簿中使用它时出现运行时错误“13”类型不匹配。想法?任何帮助表示赞赏。

Sub ExpandRows()
    Dim dat As Variant
    Dim i As Long
    Dim rw As Range
    Dim rng As Range

    Set rng = ActiveSheet.UsedRange
    dat = rng

    ' Loop thru your data, starting at the last row
    For i = UBound(dat, 1) To 1 Step -1
        ' If Quantity > 1
        If dat(i, 1) > 1 Then
            ' Insert rows to make space
            Set rw = rng.Rows(i).EntireRow
            rw.Offset(1, 0).Resize(dat(i, 1) - 1).Insert
            ' copy row data down
            rw.Copy rw.Offset(1, 0).Resize(dat(i, 1) - 1)
            ' set Quantity to 1
            rw.Cells(1, 1).Resize(dat(i, 1), 1) = 1
        End If
    Next
End Sub
4

1 回答 1

0

我在 Excel 2007 中测试过,dat(i, 1) 可能不是数字。所以在 Resize(dat(i, 1) - 1) 中输入 mismatch。

你应该试试这个,用 IsNumeric() 检查:

Sub ExpandRows()
  Dim dat As Variant
  Dim i As Long
  Dim rw As Range
  Dim rng As Range

  Dim varVal

  Set rng = ActiveSheet.UsedRange
  dat = rng

  ' Loop thru your data, starting at the last row
  For i = UBound(dat, 1) To 1 Step -1
    ' If Quantity > 1
    varVal = dat(i, 1)
    If (IsNumeric(varVal)) Then
      If (varVal > 1) Then
        ' Insert rows to make space
         Set rw = rng.Rows(i).EntireRow
         rw.Offset(1, 0).Resize(varVal - 1).Insert
         ' copy row data down
         rw.Copy rw.Offset(1, 0).Resize(varVal - 1)
         ' set Quantity to 1
         rw.Cells(1, 1).Resize(varVal, 1) = 1
      End If
    End If
  Next
End Sub
于 2013-11-10T11:29:55.340 回答