我在Excel中编写了这个非常简短的VBA宏,它将2个Range对象传递给我自己的Function。这是整个代码:
Sub Cmp()
Dim OneMatch As Boolean
Dim NoMatches As Integer
Dim OneCell, TwoCell As Range
For Each OneCell In Range("X030Pols").Cells
OneMatch = False: NoMatches = 0
For Each TwoCell In Range("X206Pols").Cells
TwoCell.Offset(0, 23).Value = 0
Next
For Each TwoCell In Range("X206Pols")
If TwoCell.Offset(0, 22).Value = "" Then
TwoCell.Offset(0, 23).Value = PolComp(OneCell, TwoCell)
If TwoCell.Offset(0, 23).Value > 0 Then
NoMatches = NoMatches + 1
End If
End If
Next
If NoMatches = 1 Then
TwoCell.Offset(0, 22).Value = OneCell.Offset(0, -1).Value
OneCell.Offset(0, 22).Value = TwoCell.Offset(0, -1).Value
End If
Next
End Sub
Private Function PolComp(Acell As Range, Bcell As Range) As Integer
If Left(Acell.Offset(0, 1).Value, 4) = Left(Bcell.Offset(0, 1).Value, 4) Then
PolComp = PolComp + 50
End If
If Acell.Offset(0, 6).Value = Bcell.Offset(0, 6).Value And Acell.Offset(0, 6).Value <> "" Then
PolComp = PolComp + 50
End If
If Acell.Offset(0, 8).Value = Bcell.Offset(0, 8).Value Then
PolComp = PolComp + 50
End If
End Function
但是当我尝试运行它时,我收到此错误:
所以OneCell定义为Range,我的函数使用Range,但是不匹配。在它运行任何内容之前尝试解析我的代码时会发生错误。
我可以解决这个问题但是我更关心理解我做错了什么。
答案 0 :(得分:5)
问题在于你的变量声明:
Dim OneCell, TwoCell As Range
这与写作相同:
Dim oneCell as Variant
Dim TwoCell as Range
相反:
Dim oneCell as Range
Dim TwoCell as Range
或者:
Dim OneCell as Range, TwoCell As Range
这样VBA就不必猜测你的类型了。