2014-05-06 78 views
0

我想輸入一系列單元格地址到VBA中的數組中。數組範圍地址

我的代碼目前狀態:

Do 
    Range1 = Application.InputBox(Prompt:="Please select the cell to add to the Array. Press ""Cancel"" when all Ranges have been added.", Title:="Range Select", Type:=8) 
    If Range1 <> False Then 
     ReDim Preserve TestArray(Count) 
     Set TestArray(Count) = Range1.Address 
    End If 
    Count = Count + 1 
Loop Until Range1 = False 

最後,我在尋找類似(A1,C3,D6,G8)

這是行不通的。

TestArray(I)。價值= TestArray(I).value的* 1.01

我如何創建範圍的數組:

然後,我會說是這樣以後使用這些範圍?

在此先感謝

+0

如果我選擇輸入框,類型0,我會接受一個字符串,使得單元格A1將被存儲在陣列中作爲像「= R1C1」的字符串 我可以然後分析此,並使用細胞功能 但有人可能知道更好的方法? – user78913

回答

0

下面是創建和使用細胞陣列的(範圍)地址短的例子:

Sub RangeArray() 
    Dim addy() 
    addy = Array("A1", "B9", "C11", "D17") 
    For i = 0 To 3 
     Range(addy(i)).Value = i + 100 
    Next i 
End Sub 
0

這裏是你可以做什麼:

Sub test() 
    Dim TestArray() As String 
    Dim count As Integer 
    Dim Range1 As Range 
    Dim el 

    Do 
     Set Range1 = Nothing 

     On Error Resume Next 
     Set Range1 = Application.InputBox(Prompt:="Please select the cell to add to the Array." & _ 
          "Press ""Cancel"" when all Ranges have been added.", _ 
          Title:="Range Select", Type:=8) 
     On Error GoTo 0 
     'if Cancel pressed - exit do 
     If Range1 Is Nothing Then Exit Do 

     ReDim Preserve TestArray(count) 

     TestArray(count) = Range1.Address 
     count = count + 1 
    Loop While True 
    'test loop through array 
    For Each el In TestArray 
     MsgBox "Address " & el & ", Value " & Range(el).Value 
    Next el 
End Sub 

但是我個人更喜歡使用Collection而不是ReDim Preserve

Sub test2() 
    Dim TestCol As Collection 
    Dim count As Integer 
    Dim Range1 As Range 
    Dim el 

    Set TestCol = New Collection 

    Do 
     Set Range1 = Nothing 

     On Error Resume Next 
     Set Range1 = Application.InputBox(Prompt:="Please select the cell to add to the Array." & _ 
          "Press ""Cancel"" when all Ranges have been added.", _ 
          Title:="Range Select", Type:=8) 
     On Error GoTo 0 
     'if Cancel pressed - exit do 
     If Range1 Is Nothing Then Exit Do 

     TestCol.Add Item:=Range1.Address 
    Loop While True 
    'test loop through collection 
    For Each el In TestCol 
     MsgBox "Address " & el & ", Value " & Range(el).Value 
    Next el 
End Sub