我已经创建了一个用户窗体,它可以完美运行。用户窗体设置为打开并在单击/打开excel文件时自动运行。它还会自动隐藏excel应用程序,以便用户只能与UserForm交互,而不能与工作簿交互。现在,我要做的最后一件事是向表单添加一个按钮,以便用户可以根据需要访问工作簿。当前,我有这段代码在退出UserForm之前显示一个消息框。当用户对问题选择“是”时,它将打开工作簿/ excel应用程序,然后突然提示一个框,“是否要保存对'FileName.xlsm'的更改?”带有“保存,不保存,取消”选项。
Private Sub btnExcel_Click()
answer = MsgBox("Are you sure you want to Exit and access the Excel
Spreadsheet?", vbYesNo + vbQuestion, "Warning!")
If answer = vbYes Then
UserForm1.Hide
Application.Visible = True
End If
End Sub
我想知道是否有代码可以让它自动选择“取消”,以便用户可以简单地访问工作簿,而不会被这个问题所困扰。我已经尝试过了,但是它不会阻止提示框。
Private Sub btnExcel_Click()
answer = MsgBox("Are you sure you want to Exit and access the Excel
Spreadsheet?", vbYesNo + vbQuestion, "Warning!")
If answer = vbYes Then
Application.DisplayAlerts = False
UserForm1.Hide
Application.Visible = True
End If
End Sub
此外,我尝试插入
ThisWorkbook.Save
但是,这告诉SaveChanges提示进行保存,然后继续终止/关闭excel。如果有人知道如何告诉提示选择“取消”,以便退出提示并保留在工作簿中,那就太好了。 TIA
编辑:我在 ThisWorkbook 下有此代码,其中包括 Workbook_Open 的代码。该代码应在单独的Excel应用程序上打开此特定工作簿,以允许其他Excel工作簿在不被隐藏的情况下打开,因为UserForm在开始时就被隐藏了。
Private Sub Workbook_BeforeClose(Cancel As Boolean)
'important to reset this
Application.IgnoreRemoteRequests = False
End Sub
Private Sub Workbook_Open()
'need to use ontime to allow xl to initialise fully
Application.OnTime Now, "ThisWorkbook.OnlyOneOfMe"
End Sub
Private Sub OnlyOneOfMe()
Dim XlApp As Excel.Application
On Error GoTo BAD
With Application
If Me.ReadOnly Or .Workbooks.Count > 1 Then
Me.ChangeFileAccess Mode:=xlReadOnly
Set XlApp = New Excel.Application
XlApp.Visible = True
XlApp.Workbooks.Open (Me.FullName)
GoTo BAD
Else
'stop opening from explorer (but not from excel)
.Visible = False
.IgnoreRemoteRequests = True
UserForm1.Show
.Visible = True
.Quit
End If
Exit Sub
End With
BAD: If Err Then MsgBox Err.Description, vbCritical, "ERROR"
Set XlApp = Nothing
Me.Close False
End Sub