簡體   English   中英

從另一張紙上獲取價值並將其放入數組中

[英]Get value from another sheets and put it in array

我是 vba 的新手。 我想從另一張表中獲取所有 state 和城市列表。 然后放入State和City數組中。 但是我在 state 數組中遇到錯誤,運行時錯誤“13”。 類型不匹配。

Dim State() As String
Dim City() As String
Dim LastRow As Long

Sheets("State&City").Select
LastRow = Cells(Rows.Count, "A").End(xlUp).Row
->State() = Range("A2:A" & LastRow).Value
City() = Range("B2:B" & LastRow).Value

使用以下內容:

Dim ws As Worksheet: Set ws = Sheets("State&City")
Dim State As Variant, City as Variant
Dim LastRow As Long

With ws
    LastRow = .Cells(.Rows.Count, "A").End(xlUp).Row
    State = .Range("A2:A" & LastRow)
    City = .Range("B2:B" & LastRow)
End With
  • 所以我們將值拉入Variant數組
  • 我們使用了明確的工作表參考並避免.Select

注意:這些是二維 arrays,因此在上述情況下,您可以參考.Range("C2") = State(1,1)之類的項目或第 n 個項目: .Range("C2") = State(n,1)


或者:

將值拉入單個數組,例如: StateCity

Dim ws As Worksheet: Set ws = Sheets("State&City")
Dim StateCity as variant
Dim LastRow As Long

With ws
    LastRow = .Cells(.Rows.Count, "A").End(xlUp).Row
    StateCity = .Range("A2:B" & LastRow)
End With

您現在可以參考第 n 個 state:

.Range("C2") = StateCity (n,1)

或者參考第n個城市:

.Range("C2") = StateCity (n,2)

暫無
暫無

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

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