簡體   English   中英

Excel VBA通​​過while循環查找值,存儲在數組中,並傳遞給其他子

[英]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

您的問題可以使用有關該問題的其他詳細信息。 我注意到了幾件事。

  1. 您缺少“如果不是FindName就是那么”的“如果結束”
  2. NameArray沒有傳出或傳到您的子例程中。 您是否將NameArray視為全​​球性產品?
  3. NameArray需要聲明為動態數組:Dim NameArray()As Variant。
  4. 您需要使用“ Redim Preserve NameArray(newIndxBound)”來增加數組的大小。
  5. 我建議使用“ Option Explicit”來確保已定義所有變量。
  6. 您可能考慮使用函數StrCmp進行字符串比較,而不是使用'FristAddress <> FindName.Address'。

使用全局動態數組的這段代碼可能會幫助您。

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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM