我有兩個數組:一個具有搜索文檔的值(arr
),另一個使用找到的值(arr2
)放入關聯的單元格地址。我對arr
沒有任何問題,並且已經在我的代碼中成功使用了它。添加到陣列並在數組中查找值
隨着arr2
,我想找到包含在arr
值的任何細胞,並從中添加行的單元格地址lRow
量下降到arr2
,但前提是該地址是不是已經在arr2
。
我找到了2個答案,我試圖結合以解決我的問題,但迄今沒有運氣。
Excel VBA - adding an element to the end of an array
How to search for string in an array
我下面的代碼:
Sub Initiate()
Dim arr(3) As Variant
arr(0) = "Value1"
arr(1) = "Value2"
arr(2) = "Value3"
arr(3) = "Value4"
Dim arr2() As Variant
Dim Alc as String
Dim lRow as Long
Dim fVal as String
lRow = Activesheet.Cells(Activesheet.Rows.Count, 1).End(xlUp).Row
For Each element In arr
fVal = element
Set fRange = WA.Cells.Find(What:=fVal, LookIn:=xlFormulas _
, LookAt:=xlPart, SearchOrder:=xlByRows, SearchDirection:=xlNext, _
MatchCase:=False, SearchFormat:=False)
While Not fRange Is Nothing
While Not IsInArray(fRange.Offset(lRow - 6, 0).Address(False, False), arr2)
ReDim Preserve arr2(0 To UBound(arr2) + 1) As Variant
arr2(UBound(arr2)) = fRange.Offset(lRow - 6, 0).Address(False, False)
Set fRange = WA.Cells.Find(What:=fVal, LookIn:=xlFormulas _
, LookAt:=xlPart, SearchOrder:=xlByRows, SearchDirection:=xlNext, _
MatchCase:=False, SearchFormat:=False)
Wend
Wend
Next element
Alc = "="
For Each element In arr2
Alc = Alc & element & "+"
Next element
Alc = Left(Alc, Len(Alc) - 1)
MsgBox Alc
End Sub
Function IsInArray(stringToBeFound As String, arr2 As Variant) As Boolean
IsInArray = (UBound(Filter(arr2, stringToBeFound)) > -1)
End Function
運行時我得到以下錯誤:
在這行代碼(T內他IsInArray
功能):
IsInArray = (UBound(Filter(arr2, stringToBeFound)) > -1)
任何幫助,不勝感激!
你有沒有考慮用字典來替換'arr2'。如果您將唯一值存儲爲密鑰,則可以相對輕鬆地防止重複。 – user3561813