提问人:Hallvard Skrede 提问时间:10/8/2023 更新时间:10/26/2023 访问量:58
Excel VBA:将多维数组的一个“列”或“行”与另一个数组进行比较
Excel VBA: Compare one "column" or "row" of a multi-dimensional array with another one
问:
我正在尝试将数组的一个“列”与另一个“列”进行比较,而不必进行循环检查整个列......
我找到了适用于特定格式(“code-1”)数组的方法*:
For intColumn = 2 To intNumOfColumns
If Join(arrArrayToChecK(intColumn), ":-^") = Join(arrArrayToChecK(intColumn - 1), ":-^") Then
etc.
但是,数组中的每个“维度”或“列”都必须按 (x)(y) 而不是 (x,y) 格式化,如以下代码片段所示:
对于第一个数组,每个维度/列的大小可能不同。同时,第二个数组具有“二次维度”,即数组的每一列/维度都有相同数量的行。问题 1 (q-1):谁能帮我获得适用于后一种情况的类似代码?
另一个相关的问题(q-2)是:如果我想比较一个数组的“行”(假设用“有效”的格式),会有类似的方法吗?我知道我可以从一开始就以不同的方式构建数组,将行变成列等,但我希望这个问题的变体没有“几乎重复”的代码......
从这里可以看出,如果我尝试转置数组,则无法再连接它(弹出错误消息)。- 现在的格式也是 (x,y) 在这里,等于 q-1 中的问题。所以可能,为了回答 q-2,需要先回答 q-1......
'* 分隔符是随机的 “:-^”。
也就是说,它永远不会出现在使用此代码的任何列表中(我正在将此代码片段作为我的“有用”VBA 函数库的一部分,以便它也可以在以后的实例中使用,而不仅仅是用于此特定项目)。
答:
2赞
VBasic2008
10/26/2023
#1
二维数组的两列是否相等?
示例(调用过程)
Sub AreTwoColumnsEqualTest()
' Reference the data range (no headers).
Dim wb As Workbook: Set wb = ThisWorkbook ' workbook containing this code
Dim ws As Worksheet: Set ws = wb.Sheets("Sheet1")
Dim trg As Range: Set trg = ws.Range("A1").CurrentRegion ' Table Range
Dim cCount As Long: cCount = trg.Columns.Count
Dim rCount As Long: rCount = trg.Rows.Count - 1 ' exclude headers
Dim drg As Range: Set drg = trg.Resize(rCount).Offset(1) ' Data Range
' Write the values from the data range to an array.
Dim Data() As Variant: Data = drg.Value
' Use the 'AreTwoColumnsEqual' function and print which columns are equal,
' and which are not
Dim i As Long, j As Long
For i = 1 To cCount - 1
For j = i + 1 To cCount
If AreTwoColumnsEqual(Data, i, j) Then
Debug.Print "Columns " & i & " and " & j & " are equal."
Else
Debug.Print "Columns " & i & " and " & j & " are not equal."
End If
Next j
Next i
End Sub
(有用的)函数
Function AreTwoColumnsEqual( _
Data() As Variant, _
ByVal Column1 As Long, _
ByVal Column2 As Long, _
Optional ByVal MatchCase As Boolean = False) _
As Boolean
Dim CompareMethod As Long: CompareMethod = CLng(MatchCase) + 1
Dim r As Long
For r = LBound(Data, 1) To UBound(Data, 1)
If StrComp(CStr(Data(r, Column1)), CStr(Data(r, Column2)), _
CompareMethod) <> 0 Then
Exit Function
End If
Next r
AreTwoColumnsEqual = True
End Function
结果
Columns 1 and 2 are not equal.
Columns 1 and 3 are not equal.
Columns 1 and 4 are not equal.
Columns 1 and 5 are equal.
Columns 2 and 3 are not equal.
Columns 2 and 4 are equal.
Columns 2 and 5 are not equal.
Columns 3 and 4 are not equal.
Columns 3 and 5 are not equal.
Columns 4 and 5 are not equal.
评论
0赞
Hallvard Skrede
10/27/2023
多谢!:)我将尝试合并到我的旧代码中:)但我不会“关闭线程”,因为我想其他人也可能在寻找答案:如何通过一些“更简单”/“更紧凑的代码”来更改数组的格式:(x)(y) 而不是 (x,y),或者 -通过可能在过程开始时指定一些东西,等等。再次感谢您的帮助。
评论
Join
Transpose
Join