Excel VBA Range对象作为参数

我在Excel中写了这个非常简短的VBAmacros,它将2个Range对象传递给我自己的函数。 这是整个代码:

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,但是有一个不匹配。 发生错误,因为它试图parsing我的代码之前运行任何东西。

我可以解决它,但我更关心理解我做错了什么。

问题出在你的variables声明中:

 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不必猜测你的types。