动态创建并为变量赋值?

时间:2014-02-27 18:24:39

标签: vba excel-vba excel-2007 excel

我有264列数据,我需要将每个数据单独设置为一个Range来将值存储在变量中......所以我想的是:

For i = 1 To 5

If i = 1 Then
    search1 = Sheets(tables).Range(Cells(2, i), Cells(200, i))
ElseIf i = 2 Then
    search2 = Sheets(tables).Range(Cells(2, i), Cells(200, i))
ElseIf i = 3 Then
    search3 = Sheets(tables).Range(Cells(2, i), Cells(200, i))
ElseIf i = 4 Then
    search4 = Sheets(tables).Range(Cells(2, i), Cells(200, i))
ElseIf i = 5 Then
    search5 = Sheets(tables).Range(Cells(2, i), Cells(200, i))
End if

Next

(我有264个,所以我认为这样做并不好......) 我怎样才能做到这一点 ?

我试过了:

search & i = Sheets(tables).Range(Cells(2, i), Cells(200, i))
"Compiler error, expected expression"
search(i) = Sheets(tables).Range(Cells(2,i),Cells(200,i))
"Sub or Function not Defined"

仍然没有工作。

这可能吗?你们有什么提示吗?这样做的技巧?

请告诉我任何想法,我会尽可能多地提供相关信息,以便至少有一个很好的解决方案。

谢谢。

1 个答案:

答案 0 :(得分:2)

试试这段代码:

Sub test()
    Dim i As Integer, n As Integer
    Dim tables As String
    Dim search() As Variant

    n = 264
    ReDim search(1 To n)

    tables = "Sheet1"

    With ThisWorkbook.Sheets(tables)
        For i = 1 To n
            search(i) = .Range(.Cells(2, i), .Cells(200, i)).Value
        Next
    End With

End Sub
相关问题