arrays - 如何将所有值从 Vector 传递给 Sub?
问题描述
我在 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
解决方案
看这个:
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
推荐阅读
- vue.js - Vuetify $refs.form.reset 和 $refs.form.resetValidation 给出错误
- paypal - Paypal 支付 API 错误 DoDirectPayment 失败:(28)
- python - Python - 类似人类的鼠标行为
- powershell - 如何强制 Powershell 查看命令的输出并等待它完成
- html - Css wont link to HTML even though it worked before
- bash - Shell脚本在后台并行运行函数并获取返回字符串
- c# - RoutingProvider.GetRoute(...) 返回 null,出了什么问题,是否有不需要 API 密钥的 GMapProvider?
- excel - Getting the sum of second column where column A contains specific characters but exclude a certain letter
- linux - Is the memory returned from mmapping /dev/shm Write-Back (WB) or Non-Cacheable Write-Combining (WC) on Linux/x86?
- python - Flip 0 and 1 bits in pandas DataFrame efficiently?