簡體   English   中英

為什么在這里出現類型不匹配錯誤?

[英]Why am I getting a type mismatch error here?

我創建一個新模塊並插入以下代碼:

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

在工作表“數據”中,我有以下代碼:

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

當我運行test()If Not Intersect(Target, Range("K:M")) Is NothingIf Not Intersect(Target, Range("K:M")) Is Nothing收到類型不匹配錯誤,因為Target錯誤類型。

為什么會這樣呢?

為什么測試觸發變更事件? 如果手動過濾數據表的第14列以僅保留空白單元格,則不會出現相同的錯誤!

類型不匹配的問題是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

根據業務邏輯,可能有幾種解決方案。

  • 最簡單的方法是編寫If Target.Cells.CountLarge > 1 Then Exit Sub_SelectionChange事件中If Target.Cells.CountLarge > 1 Then Exit Sub

  • 另一種方法是禁用周圍的事件

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

我幾乎把這個問題重復了一下。

我會以相反的順序回答您的兩個問題,以便您更好地理解。

為什么測試觸發變更事件?

我已經在導致Excel 2010中的SheetSelectionChange事件的SpecialCells中對此進行了解釋

當我運行test()子程序時,如果目標不正確,則在If Not Intersect(Target,Range(“ K:M”))Nothing上收到類型不匹配錯誤。 為什么會這樣呢?

Test過程觸發Worksheet_SelectionChange事件時,您的代碼將失敗

If Not Intersect(Target, Range("K:M")) Is Nothing And Target.Value <> "" Then

這是因為Target.Value <> ""SpecialCells(xlCellTypeBlanks).Count的罪魁禍首SpecialCells(xlCellTypeBlanks).Count可能返回多個單元格。

如果您將上述行分為兩行,則不會出現錯誤

Private Sub Worksheet_SelectionChange(ByVal Target As Range)
    If Target.Cells.CountLarge > 1 Then Exit Sub
    If Not Intersect(Target, Range("K:M")) Is Nothing Then
        If Target.Value <> "" Then
             'code
        End If
    End If
End Sub

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM