无法从传入的工作表中访问Sub中的单元格

时间:2017-04-29 17:24:00

标签: excel vba excel-vba runtime-error worksheet

我试图编写一个自定义的DeleteRows Sub,我可以从我的代码中的各个点调用,但是我遇到的问题是我传入的工作表似乎没有任何单元格与之相关联,并遇到" Type Mismatch"运行时出错。我正在排序以获得一个值出现在开头,然后循环查看它出现的单元格数,然后删除这些行。

Option Explicit

Public Sub DeleteRows(ByRef MySheet As Worksheet, RowsToDelete As Long, ColumnToUse As String, ValueToSearch As String, UseAsInt As Boolean)
    Dim MyLong As Long
    If UseAsInt Then 'We are looking for a numeric value
        MyLong = CLng(ValueToSearch)
        Do While MySheet.Cells(RowsToDelete, ColumnToUse).Value = MyLong
            RowsToDelete = RowsToDelete + 1
        Loop
    Else
        Do While MySheet.Cells(RowsToDelete, ColumnToUse).Value = ValueToSearch
            RowsToDelete = RowsToDelete + 1
        Loop
    End If
    If RowsToDelete > 2 Then 'If the row is 2 then no rows were found
        MySheet.Rows(2 & ":" & RowsToDelete - 1).Delete 'Delete the rows up to the lastRowToDelete minus 1 row(because it started at 2)
    End If
End Sub

我从另一个Sub调用它:

Dim CurDay as Worksheet
Set CurDay = Sheets("Current Day")

Call DeleteRows(CurDay, 2, "L","#N/A", False)

然而,当我在DeleteRows Sub中向MySheet添加一个监视时,它表示阵列中没有单元格,并且我收到类型不匹配错误。我在哪里错了?有时来自C#/ VB.Net背景的VBA令人沮丧......

更新:发现我必须检查.Text而不是.Value或.Value2并且它有效......

1 个答案:

答案 0 :(得分:1)

那不是你应该如何比较错误单元格。当单元格为#N/A时,您无法将其与字符串或数字等其他内容进行比较。您应首先使用IsError(cel)检查该值是否为错误。

或者,您可以使用.Text属性,该属性适用于错误的单元格,返回"#N/A"字符串而不是Error Variant

然后,您必须面对将字符串与数字进行比较的问题。最简单,删除UseAsInt参数;始终使用字符串并与.Text属性进行比较。

Public Sub DeleteRows(ByRef MySheet As Worksheet, RowsToDelete As Long, ColumnToUse As String, ValueToSearch As String)
  Do While MySheet.Cells(RowsToDelete, ColumnToUse).Text = ValueToSearch
      RowsToDelete = RowsToDelete + 1
  Loop
  If RowsToDelete > 2 Then 'If the row is 2 then no rows were found
      MySheet.Rows(2 & ":" & RowsToDelete - 1).Delete 'Delete the rows up to the lastRowToDelete minus 1 row(because it started at 2)
  End If
End Sub