0

まず、どなたでもご協力いただければ幸いです。ユーザーに数字キーを入力するためのフォームを提供するマクロを作成しています。フォームはスプレッドシートでキーを検索し、そのキーに関連付けられた対応する名前を返します。データはキーごとに複数の名前を持つことができ、キーによって異なります。.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
4

1 に答える 1

1

あなたの質問は、問題に関する追加の詳細を使用できます。気になった点をいくつか。

  1. 「If not FindName Is Nothing Then」の「End If」がありません
  2. NameArray が渡されたり、サブルーチンに渡されたりしません。NameArray をグローバルとして宣言しましたか?
  3. NameArray は動的配列として宣言する必要があります: Dim NameArray() As Variant.
  4. 配列のサイズを増やすには、「Redim Preserve NameArray(newIndxBound)」を使用する必要があります。
  5. 「Option Explicit」を使用して、すべての変数が定義されていることを確認することをお勧めします。
  6. 「FristAddress <> FindName.Address」の代わりに、文字列比較に関数 StrCmp を使用することを検討してください。

グローバル動的配列を使用したこのコードは、あなたを助けるかもしれません。

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
于 2013-06-03T14:34:40.277 に答える