Concat两个变量名称以获取第三个变量的名称

时间:2019-03-29 12:03:45

标签: excel vba variables

我正在尝试通过将搜索词应用于名为FindText的变量来使其遍历整个搜索词,该变量每次循环通过时递增1。

Dim FindText1 As String, FindText2 As String, ListText As String
Dim FindText As Variant

FindText1 = "Name"
FindText2 = "Surname"

For i = 1 To 2

    Dim Onecell As Range

    FindText = "FindText" & i

    For Each Onecell In Range("A1:AA1")
        If InStr(UCase(Onecell.Text), UCase(FindText)) > 0 Then
            ListText = ListText + vbNewLine + Onecell.Address(RowAbsolute:=False, ColumnAbsolute:=False) + " | " + Onecell.Value
        End If
    Next Onecell

    MsgBox ListText, vbQuestion, FindText

Next i

每次运行此命令时,InStr公式中的FindText变量均显示为Text,第一个实例为“ FindText1”,第二个实例为“ FindText2”。但是它实际上并没有返回变量FindText1或FindText2。

我也尝试使用以下内容:

If InStr(UCase(Onecell.Text), UCase("FindText" & i)) > 0 Then

但这也不起作用。

有可能实现这一目标吗?

3 个答案:

答案 0 :(得分:0)

这里是一个例子,但是您应该阅读数组,因为它们有很多东西,例如here

Sub x()

Dim ListText As String
Dim FindText(1 To 2) As String
Dim Onecell As Range

FindText(1) = "Name"
FindText(2) = "Surname"

For i = LBound(FindText) To UBound(FindText)
    For Each Onecell In Range("A1:AA1")
        If InStr(UCase(Onecell.Text), UCase(FindText(i))) > 0 Then
            ListText = ListText & vbNewLine & Onecell.Address(RowAbsolute:=False, ColumnAbsolute:=False) & " | " & Onecell.Value
        End If
    Next Onecell
    MsgBox ListText, vbQuestion, FindText(i)
Next i

End Sub

答案 1 :(得分:0)

这是使用数组使循环更简单的简单示例:

Sub SearchMe()
    Dim searchWords() As String
    searchWords = Split("Name,Surname,LastName,First Name,AnotherName")

    Dim searchRange As Range
    Set searchRange = ThisWorkbook.Sheets("Sheet1").Range("A1:AA1")

    Dim listText As String
    Dim word As String
    For Each word In searchWords
        Dim cell As Range
        For Each cell In searchRange
            If InStr(UCase(cell.Text), UCase(word)) > 0 Then
                listText = listText & vbNewLine & _
                           cell.Address(RowAbsolute:=False, ColumnAbsolute:=False) & _
                           " | " & cell.Value
            End If
        Next cell
        MsgBox listText, vbQuestion, word
    Next word
End Sub

答案 2 :(得分:0)

您也可以使用集合而不是数组。使用集合非常简单,我经常发现比数组更容易,更快地实现。

Dim colFind As New Collection
dim i As integer
Dim ListText As String

' Add the words you wish to search for to the collection.
colFind.Add "Name"
colFind.Add "Surname"

For i = 1 To colFind.Count

    Dim Onecell As Range

    For Each Onecell In Range("A1:AA1")
        If InStr(UCase(Onecell.Text), UCase(colFind(i))) > 0 Then
            ListText = ListText & vbNewLine & Onecell.Address(RowAbsolute:=False, ColumnAbsolute:=False) & " | " & Onecell.Value
        End If
    Next Onecell

    MsgBox ListText, vbQuestion, colFind(i)

Next i