[英]Excel VBA: Type Mismatch
我一直在使用下面概述的代码; 但是,调试器有时会抛出“类型不匹配”错误。 此代码仅比较两个工作表(A和B,它们在同一工作簿中),并突出显示工作表B上的差异(通过突出显示黄色单元格)。 如何摆脱“类型不匹配”错误?
另外,请务必注意,工作表的格式完全相同,并且每一列的数据均始于第12单元格。
任何帮助将非常感激。
Option Explicit
Sub Compare_Tracker()
Dim varSheetA As Variant
Dim strRangeToCheck As String
Dim iRow As Long
Dim iCol As Long
strRangeToCheck = "A12:K150"
varSheetA = Worksheets("Main").Range(strRangeToCheck)
varSheetB = Worksheets("Discrepancy Compare").Range(strRangeToCheck) ' or whatever your other sheet is.
For iRow = LBound(varSheetA, 1) To UBound(varSheetA, 1)
For iCol = LBound(varSheetA, 2) To UBound(varSheetA, 2)
If varSheetA(iRow, iCol) <> varSheetB(iRow, iCol) Then
' Cells are different.
' Highlight different cells yellow.
Worksheets("Discrepancy Compare").Cells(iRow + 11, iCol).Interior.ColorIndex = 36
End If
Next iCol
Next iRow
End Sub
好吧,这里有一个关于理解变量类型的课程。 。 您收到“ 类型不匹配”错误,因为在某些范围内类型无法匹配。 我正在提供代码的修改版本,以更好地理解Type的概念并解决该问题。
例如。 字符串不能与数字进行比较。 不能比较字符串或数字错误。
在下面的解决方案中,我们将首先使用VarType比较类型,并在它们的类型匹配成功之后,再执行第二级匹配。
Option Explicit
Sub Compare_Tracker()
Dim varSheetA As Variant, varSheetB as Variant
Dim strRangeToCheck As String
Dim iRow As Long
Dim iCol As Long
strRangeToCheck = "A12:K150"
varSheetA = Worksheets("Main").Range(strRangeToCheck)
varSheetB = Worksheets("Discrepancy Compare").Range(strRangeToCheck) ' or whatever your other sheet is.
For iRow = LBound(varSheetA, 1) To UBound(varSheetA, 1)
For iCol = LBound(varSheetA, 2) To UBound(varSheetA, 2)
If VarType(varSheetA(iRow, iCol)) = VarType(varSheetB(iRow, iCol)) Then
If varSheetA(iRow, iCol) <> varSheetB(iRow, iCol) Then
' Cells are different.
' Highlight different cells light yellow.
Worksheets("Discrepancy Compare").Cells(iRow + 11, iCol).Interior.ColorIndex = 36
End If
Else
' Cells Type are different.
' Highlight different cells light red.
Worksheets("Discrepancy Compare").Cells(iRow + 11, iCol).Interior.ColorIndex = 38
End If
Next iCol
Next iRow
End Sub
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.