簡體   English   中英

如何在循環中將值/范圍添加到數組?

[英]How can I add values/range to an array in a loop?

我在VBA中有以下循環:

For i = 1 To Range("B" & "65536").End(xlUp).Row Step 1

        Companies = Range("A" & i).Value
Next i

MsgBox Companies 'Output Company Name (One time)

因此,上述循環遍歷行,所有行在“ A”列中都有公司名稱。 我想將所有這些公司名稱添加到數組中,以便稍后(在循環之后)將它們全部打印出來

如何將Companies值動態添加到數組中,並在以后使用?

你不需要循環

試試這個:

Dim DirArray As Variant
DirArray = Range("A1:A5000").Value

我認為您正在尋找類似這樣的東西。

Sub tgr()

    'Declare variables
    Dim ws As Worksheet
    Dim Companies As Variant
    Dim i As Long

    'Always fully qualify which workbook and worksheet you're looking at
    Set ws = ActiveWorkbook.ActiveSheet

    'You can assing a Variant variable to the value of a range
    '  and it will populate the variable as an array if there
    '  is more than one cell in the range
    'Note that I am going off of column B as shown in your original code,
    '  and then using Offset(, -1) to get the values of column A
    Companies = ws.Range("B1", ws.Cells(ws.Rows.Count, "B").End(xlUp)).Offset(, -1).Value

    If IsArray(Companies) Then
        'More than one company found, loop through them
        For i = LBound(Companies, 1) To UBound(Companies, 1)
            MsgBox "Company " & i & ":" & Chr(10) & _
                   Companies(i, 1)
        Next i
    Else
        'Only one company found
        MsgBox Companies
    End If

End Sub

如果您需要一個數組,該數組每次都會增加並且仍然保存其內容,則應執行以下操作:

Option Explicit
Public Sub TestMe()        
    Dim i           As Long
    Dim companies() As Variant        
    ReDim companies(0)        
    For i = 1 To 20
        ReDim Preserve companies(UBound(companies) + 1)
        companies(UBound(companies)) = Range("A" & i)
    Next i        
End Sub

如果只需要將值帶到數組中,則@Leo R.的答案可能是實現它的最簡單方法。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM