显示msgbox Excel VBA

时间:2018-06-11 22:27:22

标签: excel vba excel-vba loops

我完成项目的任务几乎完成,我只是面对我的代码的最后一个问题。

Sub DeletePatientCheck()
'check if patient record exists before deleting'
Dim s As Worksheet
On Error Resume Next
'Check if Patient Record already exists'
For Each s In Sheets
    If s.Name = Selection Then
    Worksheets(s.Name).Activate
    Call DeleteRecord
End If
Next s
MsgBox "*No Patient Record Found!*"

End Sub

Sub DeleteRecord()
'Confirm delete?'
Answer = MsgBox("Are you sure you want to delete this Patient Record?", 
vbQuestion + vbYesNo, "Delete Patient Record")

If Answer = vbNo Then GoTo Skip
If Answer = vbYes Then
'It's benny, lets just double check'
Answer = MsgBox("Are you absolutely sure!", vbQuestion + vbYesNo, "Delete 
Patient Record - AYS")
If Answer = vbNo Then GoTo Skip
If Answer = vbYes Then
ActiveSheet.Delete
Sheets("Menu").Select
MsgBox "*Patient Record has been deleted - If done in error please use 
previous document version*"
End If
End If
Skip:
Sheets("Menu").Select
End Sub

基本上,当用户在子DeleteRecord()下的Answer msg框中提交“no”响应时,代码当前将其返回到sub deletepatientcheck并转到msg框“No Patient Record found”。即使找到记录也会发生这种情况。

我要做的是,如果没有给出响应,则会弹出一个不同的消息框,说“删除请求已取消”而不是MsgBox“ No Patient Record Found!”。但无论IF / then函数或Skip:我使用它总是显示“找不到患者记录”的消息框。有人可以帮忙吗?如果需要,很乐意进一步解释。提前谢谢。

1 个答案:

答案 0 :(得分:0)

这对你有用。在显示Boolean之前检查Exists变量MsgBox的值。

Sub 1:

Sub DeletePatientCheck()
'check if patient record exists before deleting'
Dim s As Worksheet
On Error Resume Next
'Check if Patient Record already exists'
Dim Exists As Boolean
For Each s In Sheets
    If s.Name = Selection Then
        Worksheets(s.Name).Activate
        Call DeleteRecord
        Exists = True
    End If
Next s

If Not Exists Then MsgBox "*No Patient Record Found!*"

End Sub

Sub 2:(建议)您只需编码vbNo,并使用vbYes语句来解决{Else,就可以避免对vbNo进行编码1}}。

另请注意,您可以通过立即调用任务然后使用GoTo Skip:来避免使用Exit Sub方法。 This link详细介绍了Goto。

Sub DeleteRecord()
'Confirm delete?'
Dim Answer As String, Answer1 As String
Answer = MsgBox("Are you sure you want to delete this Patient Record?", vbQuestion + vbYesNo, "Delete Patient Record")

If Answer = vbYes Then
    Answer1 = MsgBox("Are you absolutely sure!", vbQuestion + vbYesNo, "Delete Patient Record - AYS")
        If Answer1 = vbYes Then
            ActiveSheet.Delete
            Sheets("Menu").Select
            MsgBox "*Patient Record has been deleted - If done in error please use previous document version*"
        Else
            MsgBox ("Delete Request Cancelled")
            Sheets("Menu").Select
            Exit Sub
        End If
Else
    MsgBox ("Delete Request Cancelled")
    Sheets("Menu").Select
    Exit Sub
End If

End Sub