class级将无法工作

我正在学习使用VBA中的类。 我试图写一个获得真正使用的范围。 我在类模块中的代码如下所示:

Option Explicit Private mySheet As Range Public Property Get clTrueUsedRange() As Range Set clTrueUsedRange = TrueUsedRange(mySheet) End Property Public Property Let clTrueUsedRange(ByRef wsSource As Range) mySheet = wsSource End Property Private Function TrueUsedRange(ByRef wsSource As Worksheet) As Range Dim rLastCell As Range With wsSource Set rLastCell = .Cells.Find(What:="*", After:=.Cells(1, 1), LookIn:=xlFormulas, LookAt:= _ xlPart, SearchOrder:=xlByRows, SearchDirection:=xlPrevious, MatchCase:=False) Set TrueUsedRange = .Range("$A$1:" & rLastCell.Address) End With End Function 

当我尝试运行它时,我收到一条错误消息,指出:ByReftypes不匹配

在我的代码中有什么不正确的地方?

您的function需要一张表,而不是一个Range 。 您需要: Set clTrueUsedRange = TrueUsedRange(mySheet.Worksheet)或更改您的代码,并在调用时传递一个Worksheet。 此外,你的Property Let需要成为一个Property Set因为你正在分配一个对象:

 Option Explicit Private mySheet As Worksheet Public Property Get clTrueUsedRange() As Range Set clTrueUsedRange = TrueUsedRange(mySheet) End Property Public Property Set Sheet(ByRef wsSource As Worksheet) Set mySheet = wsSource End Property Private Function TrueUsedRange(ByRef wsSource As Worksheet) As Range Dim rLastCell As Range With wsSource Set rLastCell = .Cells.Find(What:="*", After:=.Cells(1, 1), LookIn:=xlFormulas, LookAt:= _ xlPart, SearchOrder:=xlByRows, SearchDirection:=xlPrevious, MatchCase:=False) Set TrueUsedRange = .Range("$A$1:" & rLastCell.Address) End With End Function 

然后使用: Set rData.Sheet = ActiveSheet