【问题标题】:How to pass all values from a Vector to a Sub?如何将所有值从 Vector 传递给 Sub?
【发布时间】:2020-12-09 17:47:54
【问题描述】:

我在 B2:D4 范围内的 3x3 矩阵中有整数值。

我做了一个嵌套循环检查每个单元格,直到找到一个空单元格(每行读取的停止条件)。

我可以从每个单元格中读取值并存储在向量的位置,但是当我检查向量中包含的值时,只显示向量最后一个位置的值。

我需要将所有值传递给可以处理这些小向量的子例程。

Option Explicit
Option Base 1

Sub Main()

    Dim vet(1 to 3) As Variant
    Dim lin As Long
    Dim col As Long
    Dim i As Long

    Sheets("Sheet1").Select
    lin = 2
    col = 2
    i = 1

    Cells(lin, col).Activate

    Do Until Cells(lin, 1) = ""
        col = 2
        Do Until Cells(lin, col) = ""
            Cells(lin, col).Select
            vet(i) = Cells(lin, col).Value
            col = col + 1
        Loop
        ' At this point, when checking the vector, only contains the last value
        Call showVet(vet())
        lin = lin + 1
    Loop
End Sub

Sub showVet(ByRef v() As Variant)
    Dim i As Long
    For i = 1 To 3
        Debug.Print (v(i))
    Next i
    ' And at this point, only the last value that was passed ...
End Sub

【问题讨论】:

  • vet(i) = Cells(lin, col).Value行中为变量赋值后,需要增加i的值
  • 您在内部循环中缺少i=i+1

标签: arrays excel vba vector


【解决方案1】:

看看这个:

Option Base 1

Sub Main()

Dim vet(1 To 3) As Variant
Dim lin As Long
Dim col As Long
Dim i As Long

With Sheets("Sheet1")
    lin = 2

    Do Until Cells(lin, 1) = ""
        i = 1
        col = 2
        Do Until Cells(lin, col) = ""
            .Cells(lin, col).Select
            vet(i) = Cells(lin, col).Value
            i = i + 1
            col = col + 1
        Loop

        Call showVet(vet())
        lin = lin + 1
    Loop
End With

End Sub

Sub showVet(ByRef v() As Variant)
Dim i As Long
    For i = 1 To 3
        Debug.Print (v(i))
    Next i
End Sub

【讨论】:

    猜你喜欢
    • 2021-02-06
    • 2023-03-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-05-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多