【问题标题】:VBA - Avoid error when cancel getfolderVBA - 取消getfolder时避免错误
【发布时间】:2017-02-16 21:25:05
【问题描述】:

我在取消选择文件夹时遇到基本错误。我只想在按下取消按钮时退出 Sub。

我正在使用以下代码

Set recsFolder = fso.GetFolder(Functions.GetFolder("C:\"))

Function GetFolder(strPath As String) As String
Dim Fldr As FileDialog
Dim sItem As String
Set Fldr = Application.FileDialog(msoFileDialogFolderPicker)
With Fldr
    .Title = "Select a Folder"
    .AllowMultiSelect = False
    .InitialFileName = strPath
    If .Show <> -1 Then GoTo NextCode
    sItem = .SelectedItems(1)
End With
NextCode:
GetFolder = sItem
Set Fldr = Nothing
End Function

【问题讨论】:

  • 当你点击调试时你落在哪一行?
  • 这是因为您的 recsFolder 功能失效。尝试将其插入函数中,然后他们将 Fldr 与 false 进行比较?或者按取消键是什么

标签: vba excel


【解决方案1】:

来自最佳来源之一的建议:http://www.cpearson.com/excel/browsefolder.aspx

Function BrowseFolder(Title As String, _
                Optional InitialFolder As String = vbNullString, _
                Optional InitialView As Office.MsoFileDialogView = msoFileDialogViewList)_
                As String
    Dim V As Variant
    Dim InitFolder As String
    With Application.FileDialog(msoFileDialogFolderPicker)
        .Title = Title
        .InitialView = InitialView
        If Len(InitialFolder) > 0 Then
            If Dir(InitialFolder, vbDirectory) <> vbNullString Then
                InitFolder = InitialFolder
                If Right(InitFolder, 1) <> "\" Then
                    InitFolder = InitFolder & "\"
                End If
                .InitialFileName = InitFolder
            End If
        End If
        .Show
        On Error Resume Next
        Err.Clear
        V = .SelectedItems(1)
        If Err.Number <> 0 Then
            V = vbNullString
        End If
    End With
    BrowseFolder = CStr(V)
End Function

【讨论】:

    【解决方案2】:

    错误发生在

    Set recsFolder = fso.GetFolder(Functions.GetFolder("C:\"))
    

    因为您的函数GetFolder 在您取消文件夹选择时返回一个空字符串

    快速解决方案,只需将您的逻辑更改为:

    Dim strReturned As String
    strReturned = Functions.GetFolder("C:\")
    
    If strReturned <> "" Then
        Set recsFolder = fso.GetFolder(strReturned)
    End If
    

    如果文件夹为空,则绕过Set recsFolder

    【讨论】:

      【解决方案3】:

      我已阅读您的所有答案并感谢您,但我无法应用它们。相反,我使用了错误处理(我知道我应该避免,但它不会损坏代码)。

              On Error GoTo ErrHandlr:
          Set recsFolder = fso.GetFolder(Functions.GetFolder("C:\"))
      ErrHandlr:
      Exit Sub
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-04-11
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多