从另一个表中获取价值并将其放入数组

时间:2019-10-30 07:50:14

标签: arrays excel vba

我是vba的新手。我想从另一张纸上得到所有州和城市的清单。然后将其放入州和市数组。但是我在状态数组上出错了 运行时错误'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

1 个答案:

答案 0 :(得分:1)

使用以下内容:

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

注意:这是二维数组,因此在上述情况下,您可以引用类似.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个状态:

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

或通过以下方式引用第n个城市

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