使用endif取消对话框不起作用

时间:2014-08-13 12:31:46

标签: excel-vba vba excel

所以我的代码在我放入最终之前就可以了,但是一旦我尝试实现条件,如果选择了取消,我得到一个"否则没有"编译错误或类似的东西。我基本上试图做this

这是我正在谈论的代码部分:

Public Function ChooseFolder()
'Declaring variables
Dim fldr As FileDialog
Dim sItem As String

'Folder selection
Set fldr = Application.FileDialog(msoFileDialogFolderPicker)
With fldr
    .Title = "Select a Folder"
    .AllowMultiSelect = False
    .InitialFileName = strPath
    If .Show <> -1 Then GoTo NextCode
    sItem = .SelectedItems(1)

NextCode:
    ChooseFolder = sItem
    Set fldr = Nothing

    Else
    MsgBox ("You did not select any folders")
    End If

End With

End Function

好的,所以上面已经修复了,感谢您的帮助。我现在遇到的错误(虽然它不会阻止代码在这段中运行:

Private Sub btn_LeaveReport()
'Declaring variables
Dim objFSO As Object
Dim objFolder As Object
Dim objFile As Object
Dim i As Integer
Dim sFldr As String

'Create an instance of the FileSystemObject
Set objFSO = CreateObject("Scripting.FileSystemObject")

'Added this bc of stack overflow advice. Basically how to reference path via string
sFldr = ChooseFolder()
Set objFolder = objFSO.GetFolder(sFldr)

'Hardcoded version commented out since the above choose folder option is available
'Set objFolder = objFSO.GetFolder("D:\Administration\Time Sheets")
i = 3

'loops through each file in the directory and prints their names and path
For Each objFile In objFolder.Files
    'print file name
    Cells(i + 1, 2) = objFile.Name
    'print file path
    Cells(i + 1, 3) = objFile.Path
    i = i + 1
Next objFile
End Sub

由于某种原因,Set objFolder正在创建有关无效过程调用的运行时错误。但是,该程序仍然有效,所以我很困惑这个问题。

2 个答案:

答案 0 :(得分:1)

问题在于行

If .Show <> -1 Then GoTo NextCode

在VBA中,这已经是一个完整的IF子句,因此后来的ELSE和End If缺少起始IF子句。

答案 1 :(得分:0)

这是你在尝试的吗?

Public Function ChooseFolder()
    'Declaring variables
    Dim fldr As FileDialog
    Dim sItem As String

    'Folder selection
    Set fldr = Application.FileDialog(msoFileDialogFolderPicker)

    With fldr
        .Title = "Select a Folder"
        .AllowMultiSelect = False
        .InitialFileName = strPath

        If .Show = -1 Then
            sItem = .SelectedItems(1)
            ChooseFolder = sItem
        Else
            MsgBox ("You did not select any folders")
        End If
    End With

    Set fldr = Nothing
End Function