使用.Find()在列中查找特定文本

时间:2017-07-25 17:54:16

标签: excel vba excel-vba

我无法确保我的代码使用最终用户输入的内容来查找与该值相关的一组数据,并继续使用那里的代码。例如,如果用户输入“V-”作为标签号的前缀,理论上应该在代码完成后选择单元格A7。但是,代码进入运行行“MsgBox”在标签号下面找不到空白单元格,前缀为“& str&”。“,vbExclamation”并选择单元格A3,因为它包含“V-”细胞。我尝试将Matchcase更改为true但它没有帮助。我也不希望输入的值区分大小写。

enter image description here

正在使用的代码:

Private Sub Worksheet_Activate()
Dim msg As String
Dim Cell As Range
Dim str As String, firstcell As String

msg = "Would you like to find the next available tag number?"
result = MsgBox(msg, vbYesNo)
If result = vbYes Then
str = Application.InputBox("Enter The Tag Number Prefix ", "Prefix To Tag Number")
If str = "" Then Exit Sub
If Right(str, 1) <> "-" Then str = str & "-"
With Range("A:A")
Set Cell = .Find(str, lookat:=xlPart, MatchCase:=False)
If Not Cell Is Nothing Then
    firstcell = Cell.Address
    Do
        If Cell.Offset(1, 0) = "" Then
            Cell.Offset(1, 0).Select
            Exit Sub
        ElseIf InStr(LCase(Cell.Offset(1, 0)), LCase(str)) = 0 Then
            Cell.Select
            MsgBox "No blank cell was found below a tag number with prefix " & str & ".", vbExclamation
            Exit Sub
        End If
        Set Cell = .FindNext(Cell)
    Loop While Not Cell Is Nothing And firstcell <> Cell.Address
End If
End With
Else
Cancel = True
End If
End Sub

1 个答案:

答案 0 :(得分:0)

如果要查找内容以(例如)“V-”开头的单元格,则

Set Cell = .Find(str & "*", lookat:=xlWhole, MatchCase:=False)

对于以下数据:

Sub tester()
    With ActiveSheet.Columns(1)

        Debug.Print .Find("C-" & "*", lookat:=xlWhole, _
                                      MatchCase:=False).Address() '>> $A$3
        Debug.Print .Find("V-" & "*", lookat:=xlWhole, _
                                      MatchCase:=False).Address() '>> $A$5

    End With
End Sub

enter image description here