2017-07-14 89 views
1

我正在循環遍歷WS中的單元格,並希望將單元格地址添加到範圍(或數組),因爲循環找到滿足條件的單元格。我得到一個對象Requried錯誤在最後一行Set簡單的VBA:添加單元格地址範圍與聯盟?

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) 

回答

1

CellArray變量未初始化。因此最初是Nothing,而Union不能以Nothing作爲參數。另外,你不能訪問With對象(This不存在),所以你必須首先將範圍影響到一個變量。

循環體可以寫成(必須聲明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 
+0

我得到的變量未定義在'This' –

+0

@SeanKelly我沒有檢查你的代碼。它是固定的。 – cub

+0

我有41條相同的代碼行,每條代碼都引用了我需要匹配的不同彙總。除了'R'之外,還有什麼辦法可以不聲明41個不同的範圍變量?這也是我使用'With'語句的原因 –

0

試試這個

請不要使用「與」命令,因爲它使代碼難以在大多數情況下閱讀(像你的)

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