簡體   English   中英

如果在 VBA 中找不到值,則顯示消息框

[英]Show message box if value not found in VBA

我正在研究 Excel VBA 搜索框。 當在列表中找不到記錄時,如何放置消息框?

Private Sub CommandButton2_Click()
Me.TextBox1.Value = UCase(Me.TextBox1.Value)
Dim sh As Worksheet
Set sh = Sheets("Sheet1")

Dim i As Long
Dim x As Long
Dim P As Long
Me.ListBox1.Clear

For i = 2 To sh.Range("F" & Rows.Count).End(xlUp).Row
For x = 1 To Len(sh.Cells(i, 6))
P = Me.TextBox1.TextLength

If LCase(Mid(sh.Cells(i, 6), x, P)) = Me.TextBox1 And Me.TextBox1 <> "" Then

With Me.ListBox1
.AddItem sh.Cells(i, 1)
.List(ListBox1.ListCount - 1, 1) = sh.Cells(i, 2)
.List(ListBox1.ListCount - 1, 2) = sh.Cells(i, 3)
.List(ListBox1.ListCount - 1, 3) = sh.Cells(i, 4)
.List(ListBox1.ListCount - 1, 4) = sh.Cells(i, 5)
.List(ListBox1.ListCount - 1, 5) = sh.Cells(i, 6)
.List(ListBox1.ListCount - 1, 6) = sh.Cells(i, 7)
.List(ListBox1.ListCount - 1, 7) = sh.Cells(i, 8)

End With
End If
Next x
Next i

r = Sheet1.Columns("A").ColumnWidth * 7
ListBox1.ColumnWidths = "70;60;80;230;230;100;60;" & r & ";"
End Sub

這樣做。

Private Sub CommandButton2_Click()
    Me.TextBox1.Value = UCase(Me.TextBox1.Value)
    Dim sh As Worksheet
    Set sh = Sheets("Sheet1")
    
    Dim i As Long
    Dim x As Long
    Dim P As Long
    Dim n As Long
    Me.ListBox1.Clear
    
    
    For i = 2 To sh.Range("F" & Rows.Count).End(xlUp).Row
        For x = 1 To Len(sh.Cells(i, 6))
        P = Me.TextBox1.TextLength
        
        If LCase(Mid(sh.Cells(i, 6), x, P)) = Me.TextBox1 And Me.TextBox1 <> "" Then
        
            n = n + 1 '<~~ count items
        
            With Me.ListBox1
                .AddItem sh.Cells(i, 1)
                .List(ListBox1.ListCount - 1, 1) = sh.Cells(i, 2)
                .List(ListBox1.ListCount - 1, 2) = sh.Cells(i, 3)
                .List(ListBox1.ListCount - 1, 3) = sh.Cells(i, 4)
                .List(ListBox1.ListCount - 1, 4) = sh.Cells(i, 5)
                .List(ListBox1.ListCount - 1, 5) = sh.Cells(i, 6)
                .List(ListBox1.ListCount - 1, 6) = sh.Cells(i, 7)
                .List(ListBox1.ListCount - 1, 7) = sh.Cells(i, 8)
            
            End With
        End If
        Next x
    Next i
    If n Then
        MsgBox n & " Items were selected", vbInformation
    Else
        MsgBox "value not found", vbInformation
    End If
    
    r = Sheet1.Columns("A").ColumnWidth * 7
    ListBox1.ColumnWidths = "70;60;80;230;230;100;60;" & r & ";"
End Sub

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

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