使用VBA,我希望对2D数组中的每一行进行“与”运算,并在单独的1D数组中对结果加注星标,而不必对单对进行“与”运算并将结果与该行中的下一项进行“与”运算。
仅供参考,这是我第一次使用2D数组,如果有明显的解决方案,请对不起。
例如,如果我的工作表中的数据看起来像这样(实际范围要大得多):
我想做一个等于excel公式的等式:= AND(B2:D2)然后= AND(B3:D3),等等...
我有设置所有内容的代码,但是除了循环遍历一行的每个元素,存储结果然后循环遍历下一个等等之外,我不知道如何继续。我希望这里有一个更好(更有效)的进行方式。
到目前为止,这是我的代码
Sub Exceptions()
' Setup worksheet
Dim wks As Worksheet
Set wks = cnTest
' Find last row of range
Dim LastRow As Long
LastRow = Find_LastRow(wks) 'Functionthat returns last row
' load range into array
Dim MyArray As Variant
MyArray = wks.Range("B2:D8")
' Setup 1D Result array
Dim Results As Variant
Results = wks.Range("A2:A8")
Dim i As Long
For i = 1 To LastRow
' Perform AND function on each row of the array
' then place result in 1D array (Results())
' If this were a formul: =AND(B2:D2)
'
' Is there way to "AND" across a row in and array or
' must I "AND" MyArray(1,1) with MyArray(1,2) then AND
' that result with MyArray(1,3)
Next i
End Sub
谢谢
答案 0 :(得分:3)
尝试一下。
Sub Exceptions()
' Setup worksheet
' load range into array
Dim MyArray As Variant
MyArray = ActiveSheet.Range("B2:D8")
' Setup 1D Result array
Dim Results As Variant
Results = ActiveSheet.Range("A2:A8")
Dim i As Long
Dim X As Long
For i = 1 To UBound(MyArray, 1)
Results(i, 1) = "True"
For X = 1 To UBound(MyArray, 2)
If MyArray(i, X) = False Then
Results(i, 1) = "False"
Exit For
End If
Next X
Next i
End Sub
答案 1 :(得分:1)
尝试
Sub test()
Dim vR()
Dim rngDB As Range, rng As Range
Dim i As Long, r As Long
Set rngDB = Range("b2:b8")
r = rngDB.Rows.Count
ReDim vR(1 To r)
For Each rng In rngDB
i = i + 1
vR(i) = WorksheetFunction.And(rng.Resize(1, 3))
Next rng
Range("a2").Resize(r) = WorksheetFunction.Transpose(vR)
End Sub
答案 2 :(得分:0)
在编辑栏中,键入:
=IF(-PRODUCT(IF(A1,-1,0),IF(C1,-1,0)),TRUE,FALSE)
(如果数据在A和C列中),然后向下拖动。
因为众所周知,A AND B = AB
和A
是布尔变量(请注意B
前面的减号)。