有沒有一種快速的方法來檢查變體的整行是否為空?
我的多維陣列/變體有 n 行和 m 列。
我能想到的唯一方法是遍歷(特定行的)列并使用 IsEmpty() 函式來確定單元格是否為空。
該變體僅包含字串。
你知道更快的方法嗎?也許像這樣的偽代碼:IsEmpty(myarr(1,*))
這個偽代碼意味著檢查第一行的所有列是否為空。
uj5u.com熱心網友回復:
您可以嘗試以下方法:
Sub Test()
Dim myarr() As Variant, indx As Long
myarr = Range("A8:C20").Value 'Or however you initialize your array.
indx = 1 'Or whichever row you would want to check.
With Application
Debug.Print Join(.Index(myarr, indx, 0), "") <> ""
End With
End Sub
不確定它是否會比回圈更快,因為我們稱之為作業表應用程式。
uj5u.com熱心網友回復:
不,沒有更快的方法,特別是考慮到 VBA 中的陣列按列存盤在記憶體中。單行上的值不會像列值那樣相鄰存盤在記憶體中 - 您可以通過For Each在陣列上運行回圈來輕松測驗這一點。
話雖如此,您可能應該考慮使用一個Function檢查特定行是否為空的方法,以便您可以重復呼叫它,如果需要也可以檢查空字串。例如,回傳 "" 的公式范圍不會為空,但您可能希望能夠將它們視為空。
例如,您可以使用如下內容:
Public Function Is2DArrayRowEmpty(ByRef arr As Variant _
, ByVal rowIndex As Long _
, Optional ByVal ignoreEmptyStrings As Boolean = False _
) As Boolean
Const methodName As String = "Is2DArrayRowEmpty"
'
If GetArrayDimsCount(arr) <> 2 Then
Err.Raise 5, methodName, "Array is not two-dimensional"
ElseIf rowIndex < LBound(arr, 1) Or rowIndex > UBound(arr, 1) Then
Err.Raise 5, methodName, "Row Index out of bounds"
End If
'
Dim j As Long
Dim v As Variant
'
For j = LBound(arr, 2) To UBound(arr, 2)
v = arr(rowIndex, j)
Select Case VBA.VarType(v)
Case VbVarType.vbEmpty
'Continue to next element
Case VbVarType.vbString
If Not ignoreEmptyStrings Then Exit Function
If LenB(v) > 0 Then Exit Function
Case Else
Exit Function
End Select
Next j
'
Is2DArrayRowEmpty = True 'If code reached this line then row is Empty
End Function
Public Function GetArrayDimsCount(ByRef arr As Variant) As Long
If Not IsArray(arr) Then Exit Function
'
Const MAX_DIMENSION As Long = 60
Dim dimension As Long
Dim tempBound As Long
'
'A zero-length array has 1 dimension! Ex. Array() returns (0 to -1)
On Error GoTo FinalDimension
For dimension = 1 To MAX_DIMENSION
tempBound = LBound(arr, dimension)
Next dimension
Exit Function
FinalDimension:
GetArrayDimsCount = dimension - 1
End Function
IsObject請注意,由于您的值來自 Excel 中的某個范圍,因此我沒有進行檢查,但您通常會在一般情況下進行檢查。
您的偽代碼IsEmpty(myarr(1,*))可以翻譯為:
Is2DArrayRowEmpty(myarr, 1, False) 'Empty strings would not be considered Empty
或者
Is2DArrayRowEmpty(myarr, 1, True) 'Empty strings would be considered Empty
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/414912.html
標籤:
上一篇:不能為了我的生活讓它在C 中對齊
