gpt4 book ai didi

arrays - 使用 For each Statement 循环遍历 VBA Excel 中的多维数组 - 仅第一维

转载 作者:行者123 更新时间:2023-12-04 22:18:56 25 4
gpt4 key购买 nike

我想知道是否可以循环遍历多维数组并将循环限制在第一维。
我已经制定了一个例子来说明我的观点:
我使用我在 excel 中的数据创建一个矩阵,我希望循环只打印与索引列对应的值。我尝试了不同的方法,但除了使用 if 条件退出 for 循环外,似乎没有任何效果。
Data table
这是原始代码:

Public matrix1() As Variant

Sub elements_in_loop()

Range("A3").Select
Range(Selection.End(xlToRight), Selection.End(xlDown)).Select
matrix1 = Selection

For Each Record In matrix1

Debug.Print Record

Next

End Sub

这是带有 if 条件的代码:
Public matrix1() As Variant

Sub elements_in_loop()

Range("A3").Select
Range(Selection.End(xlToRight), Selection.End(xlDown)).Select
matrix1 = Selection

For Each Record In matrix1

If Record <= UBound(matrix1) Then

Debug.Print Record

Else:

Exit For

End If

Next

End Sub

非常感谢任何关于如何在没有 if 条件的情况下执行此操作的建议。
更新:
我需要此信息的目的是在两个矩阵中查找相似记录,而不会出现“类型不匹配”错误。
这是我正在使用的数据:
黄色的记录是两个矩阵中的记录。
data updated
这是我为获取匹配的记录而编写的代码,但仍在使用 if 条件将搜索限制为仅第一维。
Public matrix1() As Variant
Public matrix2() As Variant

Sub elements_in_loop()

Range("A3").Select
Range(Selection.End(xlToRight), Selection.End(xlDown)).Select
matrix1 = Selection

Range("G3").Select
Range(Selection.End(xlToRight), Selection.End(xlDown)).Select
matrix2 = Selection

For Each Record In matrix1

If Record <= UBound(matrix1) Then

For Each Record2 In matrix2

If Record2 <= UBound(matrix2) Then

If matrix1(Record, 4) = matrix2(Record2, 4) Then

Debug.Print "There's match"
Debug.Print Record

Else: End If
Else:

Exit For

End If

Next

Else:

Exit For

End If

Next


End Sub

最佳答案

只需使用常规 for 循环并循环第一个维度:

Sub elements_in_loop()
With ActiveSheet
matrix1 = .Range(.Range("A3").End(xlToRight), .Range("A3").End(xlDown))
matrix2 = Range(Range("G3").End(xlToRight), Range("G3").End(xlDown))

Dim i As Long
For i = LBound(matrix1, 1) To UBound(matrix1, 1)
Dim j As Long
For j = LBound(matrix2, 1) To UBound(matrix2, 1)
If matrix1(i, 4) = matrix2(j, 4) Then
Debug.Print "There's match"
Debug.Print matrix1(i, 4)
End If
Next j
Next i
End With
End Sub

关于arrays - 使用 For each Statement 循环遍历 VBA Excel 中的多维数组 - 仅第一维,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66054046/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com