为什么我在这里遇到类型不匹配错误?

Dmi*_*kin 1 excel vba excel-vba

我创建一个新模块并插入此代码:

Sub test()
   Set wsData = ThisWorkbook.Worksheets("Data")
   sCount = wsData.Columns(14).SpecialCells(xlCellTypeBlanks).Count
   msgbox sCount
End Sub
Run Code Online (Sandbox Code Playgroud)

在工作表"数据"中,我有这个代码:

Private Sub Worksheet_SelectionChange(ByVal Target As Range)
    If Selection.CountLarge = 1 Then
        If Not Intersect(Target, Range("K:M")) Is Nothing And Target.Value <> "" Then
            'code
        End if
    End if
End Sub
Run Code Online (Sandbox Code Playgroud)

当我运行test()sub时,我得到一个类型不匹配错误If Not Intersect(Target, Range("K:M")) Is Nothing,因为Target错误类型.

为什么会这样?

为什么测试会触发Change Event?如果手动过滤我的数据表的第14列,只留下空白单元格,我不会得到相同的错误!

Vit*_*ata 5

类型不匹配的问题在于它Target.Cells不止一个单元格.因此,Target.Value <> ""抛出类型不匹配,因为无法比较多个单元格"".看到MsgbBox细胞数量:

Private Sub Worksheet_SelectionChange(ByVal Target As Range)
    If Selection.CountLarge = 1 Then
        If Target.Cells.CountLarge > 1 Then MsgBox Target.Cells.CountLarge
        If Not Intersect(Target, Range("K:M")) Is Nothing And Target.Value <> "" Then
            'code
        End If
    End If
End Sub
Run Code Online (Sandbox Code Playgroud)

基于业务逻辑,可能存在多种解决方案.

  • 最简单的就是写 If Target.Cells.CountLarge > 1 Then Exit Sub一下这个_SelectionChange事件.

  • 另一种方法是禁用周围的事件

sCount = wsData.Columns(14).SpecialCells(xlCellTypeBlanks).Count 像这样:


Sub TestMe()
   Set wsData = ThisWorkbook.Worksheets("Data")
   Application.EnableEvents = False
   sCount = wsData.Columns(14).SpecialCells(xlCellTypeBlanks).Count
   Application.EnableEvents = True
   msgbox sCount
End Sub
Run Code Online (Sandbox Code Playgroud)