[英]Excel VBA Find Values through while loop, store in array, and pass to different sub
首先,我感謝任何人都能提供的幫助。 我正在編寫一個宏,該宏將為用戶提供輸入數字鍵的形式。 表單將在電子表格中搜索該密鑰,並返回該密鑰所附的相應名稱。 數據每個鍵可能有多個名稱,並且會因鍵而異。 我想使用.Find和.FindNext遍歷數據,並找到附加到該鍵的所有可能名稱(我已經完成了這一部分)。 我遇到麻煩的部分是在循環期間,將每個名稱存儲在一個數組中,我可以將其傳遞給另一個子。 我想傳遞數組,以便用戶可以單擊另一個命令按鈕,並在選擇一個可能的名稱之前循環瀏覽。
Private Sub FindNameButton_Click()
Dim KeyMatch As Long
Dim NameRow As Long
FindName As Range
KeyMatch = KeyBox.Value ' The UserForm input box
With Worksheets("Master List"). Range("D:D")
Set FindName = .Find(What:= KeyMatch, LookAt:= xlWhole, LookIn:= xlValues, MatchCase:= False)
If not FindName Is Nothing Then
FirstAddress = FindName.Address
Do
Application.GoTo FindName
NameRow = ActiveCell.Row
Cells(NameRow, 2).Select 'Selects the name associated with the key identifier
NameBox.Value = ActiveCell.Value 'Fills the UserForm box with the name
' I would like to fill the array here with each name is it passes through but I have no idea how
NameArray(i) = ActiveCell.Value ' ??????
Set FindName = .FindNext(FindName)
Loop While FindName is Nothing and FristAddress <> FindName.Address
End With
End Sub
Private Sub NextNameButton_Click()
Static cnt As Long
If cnt <= Ubound(NameArray) Then
NameBox.Value = NameArray(cnt) 'Fill UserForm Name Box with name from Name Array
Else
cnt = 0
End If
cnt = cnt + 1 ' increase every time button is clicked
End Sub
您的問題可以使用有關該問題的其他詳細信息。 我注意到了幾件事。
使用全局動態數組的這段代碼可能會幫助您。
Option Explicit
Public MyArray() As Variant
Sub AddToArray()
Dim indx As Integer
For indx = 0 To 9
ReDim Preserve MyArray(indx)
MyArray(indx) = indx
Next indx
End Sub
Sub RetrieveFromArray()
Dim indx As Integer
Dim sht As Worksheet
Dim rowN As Integer
Set sht = ActiveSheet
rowN = 10
For indx = 0 To 9
sht.Cells(rowN, 3) = MyArray(indx)
rowN = rowN + 1
Next indx
End Sub
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.