令人困惑的类型不匹配错误

时间:2013-11-10 05:06:18

标签: excel vba type-mismatch

我无法弄清楚这一点。它在一个简单的测试工作簿中工作但是当我尝试在我的大型工作簿中使用它时,我得到运行时错误“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

1 个答案:

答案 0 :(得分:0)

我在Excel 2007中测试过,dat(i,1)可能不是数字。因此,Resize中的类型不匹配(dat(i,1) - 1)。

您应该尝试使用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