我正在尝试调用我创建的函数,但一直收到此错误。
'This is where I try and call the function
Sub Test1()
Dim ChartCells1 As Range
Set ChartCells1 = GetValues(ActiveSheet.Range("BV2", Range("BV2").End(xlDown)), ActiveSheet.Range("BV2"))
ChartCells1.Select
End Sub
'this is the function am trying to call
Function GetValues(Column As Range, Value As Range) As Range
Dim ChartCells As Range
Dim Count As Range
Dim Cells As Range
Dim Number As Range
DataSheetArea1Zone16.Activate
Set Number = Range(Value)
Set Cells = Range(Column)
Set ChartCells = Range(Value).Offset(0, -36)
For Each Count In Cells
If Count.Value <> Number Then
Set ChartCells = Union(ChartCells, Count.Offset(0, -36))
Set Number = Count
End If
Next Count
GetValues = ChartCells
End Function
我在GetValues = ChartCells行或ChartCells1.Select行上继续收到错误91。
答案 0 :(得分:0)
在代码中,以下是有问题的:
Set Number = Range(Value)
Set Cells = Range(Column)
Set ChartCells = Range(Value).Offset(0, -36)
'----
GetValues = ChartCells
由于Value
和Column
已被声明为范围,因此Range(Value)
导致了错误。该函数返回类型Range
,因此应进行设置,例如GetValues = ChartCells
。
通常,在VBA中使用Activate
和Select
并不是最佳实践-How to avoid using Select in Excel VBA
这可行(但是最好将ActiveSheet
和.Activate
重构):
Sub Main()
Dim ChartCells1 As Range
Set ChartCells1 = GetValues(ActiveSheet.Range("BV2", Range("BV2").End(xlDown)), ActiveSheet.Range("BV2"))
ChartCells1.Select
End Sub
'this is the function am trying to call
Function GetValues(Column As Range, Value As Range) As Range
Dim ChartCells As Range
Dim Count As Range
Dim Cells As Range
Dim Number As Range
Worksheets(1).Activate
Set Number = Value
Set Cells = Column
Set ChartCells = Value.Offset(0, -36)
For Each Count In Cells
If Count.Value <> Number Then
Set ChartCells = Union(ChartCells, Count.Offset(0, -36))
Set Number = Count
End If
Next Count
Set GetValues = ChartCells
End Function