Lef*_*fty 0 excel vba excel-vba
我在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
Run Code Online (Sandbox Code Playgroud)
但是当我尝试运行它时,我收到此错误:
所以OneCell定义为Range,我的函数使用Range,但是不匹配.在运行任何内容之前尝试解析我的代码时会发生错误.
我可以解决它,但我更关心理解我做错了什么.
问题出在你的变量声明中:
Dim OneCell, TwoCell As Range
Run Code Online (Sandbox Code Playgroud)
这与写作相同:
Dim oneCell as Variant
Dim TwoCell as Range
Run Code Online (Sandbox Code Playgroud)
代替:
Dim oneCell as Range
Dim TwoCell as Range
Run Code Online (Sandbox Code Playgroud)
要么:
Dim OneCell as Range, TwoCell As Range
Run Code Online (Sandbox Code Playgroud)
所以VBA不必猜测你的类型.