出现错误时如何制作消息框?

问题描述 投票:0回答:1

我正在尝试将信息从文本框导入到另一个工作簿(book1)中的特定工作表。 该宏将通过在 textbox1 中输入的信息找到特定的工作表。 (书1上有预先制作好的表格)完成后,会出现一个消息框,显示提交成功。

这是我的问题:

如果没有与 textbox1 中写入的内容相匹配的工作表,我如何放入显示“未找到用户”的错误消息框?

Private Sub CommandButton1_Click()
Dim Path As String
Dim Filename As String

Path = "C:\Users\OneDrive\Desktop\proj\"
Filename = "Book1" & ".xlsx"
Workbooks.Open Filename:=Path & Filename


With Workbooks(Filename).Worksheets(TextBox1.Text)
`this finds the worksheet in book1`
  .Range("A1").Value = Me.TextBox1.Text
  .Range("B1").Value = Me.TextBox2.Text
  .Range("C3").Value = Me.TextBox3.Text
  .Range("D4").Value = Me.TextBox4.Text
End With

`msgbox starts`
 MsgBox "Submitted Successfully"
ActiveWorkbook.Close _
SaveChanges:=True, _
Filename:="C:\Users\OneDrive\Desktop\proj\Book1.xlsx"
Unload Me

End Sub

接下来我尝试使用错误恢复,但我真的想要一个消息框,说它没有找到放入的内容。 我不太确定如何继续使用 if else 语句,因为我不知道在哪里可以放置任何 if else 语句。我真的希望你能帮忙。

excel vba userform
1个回答
0
投票

你可以这样做:

Private Sub CommandButton1_Click()
    'use Const for fixed values
    Const Path As String = "C:\Users\OneDrive\Desktop\proj\"
    Const Filename As String = "Book1.xlsx"
    
    Dim wb As Workbook, ws As Worksheet
    
    'get a reference to the opened workbook
    Set wb = Workbooks.Open(Filename:=Path & Filename)
    On Error Resume Next  'ignore error if no sheet matches
    Set ws = wb.Worksheets(TextBox1.Text)
    On Error GoTo 0       'stop ignoring errors
    
    If Not ws Is Nothing Then 'found the sheet?
        ws.Range("A1").Value = Me.TextBox1.Text
        ws.Range("B1").Value = Me.TextBox2.Text
        ws.Range("C3").Value = Me.TextBox3.Text
        ws.Range("D4").Value = Me.TextBox4.Text
        MsgBox "Submitted Successfully"
        wb.Close True  'save
        Unload Me
    Else
        MsgBox "No worksheet found for '" & TextBox1.Text & "'", vbExclamation
        wb.Close False 'no save
        'Unload Me '? or user corrects name on form?
    End If

End Sub
© www.soinside.com 2019 - 2024. All rights reserved.