2014-05-06 79 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