Excel VBA – 错误执行代码

我使用Application.FileDialog(msoFileDialogFolderPicker)来select一个文件夹。 这是通过在用户窗体中使用button来执行的。 但是,在用户select文件夹之前,将创build一个新的工作表。 然后popup打开文件对话框[Application.FileDialog(msoFileDialogFolderPicker)]。

Function SelectFolder(Optional msg As String) As String Dim diaFolder As FileDialog Set diaFolder = Application.FileDialog(msoFileDialogFolderPicker) diaFolder.AllowMultiSelect = False diaFolder.Title = msg diaFolder.Show On Error Resume Next SelectFolder = diaFolder.SelectedItems(1) On Error GoTo 0 Set diaFolder = Nothing End Function 

用户决定取消select文件夹时出现问题。 发生这种情况时,应该删除新创build的工作表。 我试图使用error handling程序,但现在运气。

 ErrorHandler: If SheetExists("MS") Then Application.Run "DeleteSheet.deleteSh1" If SheetExists("MS2") Then Application.Run "DeleteSheet.deleteSh2" If SheetExists("MT") Then Application.Run "DeleteSheet.deleteSh3" Application.Run "HideSheets.hideSh" Resume Next Exit Sub 

希望大家可以提出一些想法。

我想象上面的例程SelectFolder不知何故从一个子,首先创build一个工作表,然后调用它。 你可以像这样实现你的目标:

 Sub MyButton_Click() Dim newWS as worksheet, folder as String set newWS = sheets.Add folder = SelectFolder("please select your folder") If folder = "" Then newWS.Delete Else ' ... proceed with the selected folder End If End Sub 

然而,在获得用户的答案之前创build工作表在我看来并不是一个好方法,除非有很强的理由。

为什么不build立表格,当你有一个有效的回应?

这就是说,你可以检查你正在寻找的string的长度 – 0意味着取消,即

 Dim strResponse As String strResponse = SelectFolder("test") If Len(strResponse) = 0 Then MsgBox "user cancelled", vbCritical 'delete sheet End If