vba用字符串填充动态数组

时间:2015-07-24 07:42:29

标签: arrays excel vba excel-vba for-loop

嘿,我是vba的新手,我已经尝试过寻找我的问题的答案了。 我想填充一个动态数组,其中包含可在表中更改的特定数组。为此,我创建了以下代码:

Sub ZellenArrayReader()
    Dim boom() As Variant
    Dim rowsboom As Integer
    Dim sh As Variant

    sh = "TAB1"
    Worksheets(sh).Range("A1").Select
    rowsboom = Selection.CurrentRegion.Rows.Count - 2

    ReDim boom(0 To rowsboom)

    For i = LBound(boom) To i = UBound(boom)
        boom(i) = Worksheets(sh).Cells(i + 2, 1)
    Next i

    Cells(10, 5).FormulaR1C1 = boom(0)
    Cells(10, 1).FormulaR1C1 = boom(1)

End Sub

for part是无法正常工作的。即使数组的上行数为4或5,它也只运行一次代码。

3 个答案:

答案 0 :(得分:0)

您需要将For ... Next循环更改为:

For i = LBound(boom) To UBound(boom)
    boom(i) = Worksheets(sh).Cells(i+2, 1)
Next i

答案 1 :(得分:0)

小修改,效果很好。

Private Sub ZellenArrayReader()

    Dim boom() As Variant
    Dim rowsboom As Integer
    Dim sh As String

    sh = "TAB1"

    Sheets(sh).Range("A1").Select

    rowsboom = Selection.CurrentRegion.Rows.Count - 2

    ReDim boom(0 To rowsboom)

    For i = 0 To UBound(boom) Step 1
        boom(i) = Sheets(sh).Cells(i + 2, 1)
    Next i

    Cells(10, 5).FormulaR1C1 = boom(0)
    Cells(10, 1).FormulaR1C1 = boom(1)

End Sub

答案 2 :(得分:0)

正如其他人已经回答的那样,for循环的i=UBound(boom)部分导致了问题。如果繁荣有1个元素,那将返回True(i = 0和UBound(繁荣)= 0)并且它将像For i = LBound(boom) to -1(当铸造为Long时,True为-1)。这将循环零次。在您的情况下,您至少有两个元素,因此i=UBound(boom)返回False。这就像For i = LBound(boom) to 0这就是为什么它只执行一次。

Range.Value属性返回一个二维数组,通常比循环数组并用单元格中的值填充它更快。通过Range.Value分配的数组的下限是1,而不是零。这是一个没有循环的代码重写。

Sub ZellenArrayReader()

    Dim vBoom As Variant
    Dim sh As Worksheet
    Dim rCurrReg As Range

    Set sh = ThisWorkbook.Worksheets("TAB1")

    Set rCurrReg = sh.Range("A1").CurrentRegion
    vBoom = rCurrReg.Resize(rCurrReg.Rows.Count - 2).Value

    sh.Cells(10, 5).Value = vBoom(1, 1)
    sh.Cells(10, 1).Value = vBoom(2, 1)

End Sub