简单的VBA:添加单元格地址范围与联盟?

我正在循环WS中的单元格,并希望将单元格地址添加到范围(或数组),因为循环find符合条件的单元格。 我在最后一行Set得到一个Object Requried错误

 Dim CellArray As Range With ws With .Cells(Application.WorksheetFunction.Match("Total checks", .Range("A:A"), 0), Application.WorksheetFunction.Match(ComboBox1.Value,0)) .Formula = "=SUM('" & Root & sourceSheet & ws.Name & " " & monthNumber & "." & lastDay & "." & Format(Now(), "yy") & "'!$H:$H)" Set CellArray = Union(CellArray, This.Address) 

您的CellArrayvariables未初始化。 因此,最初NothingUnion也不能Nothing作为一个论点。

另外,你不能访问With对象( This不存在),所以你必须首先将范围影响到一个variables。

循环体可以被写入(你必须事先声明Dim R As Range ):

 Set R = Cells(Application.WorksheetFunction.Match("Total checks", .Range("A:A"), 0), Application.WorksheetFunction.Match(ComboBox1.Value,0)) R.Formula = "=SUM('" & Root & sourceSheet & ws.Name & " " & monthNumber & "." & lastDay & "." & Format(Now(), "yy") & "'!$H:$H)" If CellArray Is Nothing Then Set CellArray = R Else Set CellArray = Union(CellArray, R) End If 

尝试这个

请不要使用“With”命令,因为它会使代码在大多数情况下难以阅读(比如你的)

 Sub test() Dim ws As Worksheet Set ws = ActiveSheet ' or point to any worksheet here, if you want Dim CellArray As Range Dim myCell As Range ' range("a:a") must contain "Total checks", otherwise next line will fail Set myCell = ws.Cells(Application.WorksheetFunction.Match("Total checks", ws.Range("A:A"), 0), Application.WorksheetFunction.Match(ComboBox1.Value, 0)) myCell.Select ' debug ... visually verify the cell location myCell.Formula = "=SUM('" & Root & sourceSheet & ws.Name & " " & monthNumber & "." & lastDay & "." & Format(Now(), "yy") & "'!$H:$H)" If CellArray Is Nothing Then Set CellArray = myCell ' CellArray cannot be empty to start, otherwise the "union" function will fail Else Set CellArray = Union(CellArray, myCell) End If CellArray.Select ' debug ... visually verify the resulting CellArray range End Sub