“无法访问文件” 1004导出工作表错误VBA

时间:2018-06-25 10:56:42

标签: excel vba excel-vba

我无法解决错误。我搜索了SO,但找不到解决方案。该代码工作98%。仅需要解决2%。

用户窗体:
enter image description here

单击“浏览”按钮时,将打开“选择文件夹”对话框。所选的文件夹路径显示在文本框中。

代码:

Dim sItem As String

Private Sub browse_Button_Click()
Dim fldr As FileDialog
Dim strPath As String
Set fldr = Application.FileDialog(msoFileDialogFolderPicker)
With fldr
    .Title = "Select a Folder"
    .AllowMultiSelect = False
    .InitialFileName = strPath
    If .Show <> -1 Then Exit Sub
    sItem = .SelectedItems(1)
End With
showFilePath.Text = sItem
End Sub

Private Sub cancel_button_Click()
Unload Me
End Sub

Private Sub export_button_Click()
Dim FileExtStr As String
Dim FileFormatNum As Long
Dim xWs As Worksheet
Dim xWb As Workbook
Dim FolderName As String
Application.ScreenUpdating = False
Set xWb = Application.ThisWorkbook
DateString = Format(Now, "yyyy-mm-dd hh-mm-ss")
FolderName = sItem & "\" & xWb.Name & " " & DateString
MkDir FolderName

For Each xWs In xWb.Worksheets
    xWs.Copy
        If xlsx = True Then
            FileExtStr = ".xlsx": FileFormatNum = 51
            Unload Me
        ElseIf xlsm = True Then
            FileExtStr = ".xlsm": FileFormatNum = 52
            Unload Me
        ElseIf xls = True Then
            FileExtStr = ".xls": FileFormatNum = 56
            Unload Me
        ElseIf xlsb = True Then
            FileExtStr = ".xlsb": FileFormatNum = 50
            Unload Me
        ElseIf csv = True Then
            FileExtStr = ".csv": FileFormatNum = 6
            Unload Me
        ElseIf txt = True Then
            FileExtStr = ".txt": FileFormatNum = -4158
            Unload Me
        ElseIf html = True Then
            FileExtStr = ".html": FileFormatNum = 44
            Unload Me
        ElseIf prn = True Then
            FileExtStr = ".prn": FileFormatNum = 36
            Unload Me
        End If
    xFile = FolderName & "\" & Application.ActiveWorkbook.Sheets(1).Name & FileExtStr
    Application.ActiveWorkbook.SaveAs xFile, FileFormat:=FileFormatNum   '<---ERROR HERE
    Application.ActiveWorkbook.Close False
Next

MsgBox "You can find the files in " & FolderName
Application.ScreenUpdating = True
End Sub


选择文件夹以及导出工作表的格式后,最后出现错误。

错误:
enter image description here

注意:excel文件保存在E:/ VBA / AJD / Export Worksheets.xlsm中。并且工作表将被导出到其他位置(用户选择一个文件夹)。因此,运行代码的Excel文件和导出文件夹位于不同的位置。

路径:

enter image description here

1 个答案:

答案 0 :(得分:1)

当您在VBA中遇到错误时,最好的解决方案是仔细阅读错误消息框。在这种情况下,第一个建议是正确的建议-“确保指定的文件夹存在”。

检查文件夹是否存在的最简单方法是查看路径。可能的解决方案:

MsgBox xFile

将打印该文件夹,然后从此开始进行调试。通常,错误是可见的,在这种情况下,存在两个\\

enter image description here

编辑:

在这种情况下,OP可以首先检查showFilePath(浏览)是否已正确使用:

If Dir(showFilePath.Text) = "" Then
    sItem = showFilePath.Text
Else
    MsgBox "No folder selected!"
    Exit Sub
End If

第二,OP可以检查以下哪种情况:

If Right(sItem, 1) = "\" Then 'Backslash is yet present
    FolderName = sItem & xWb.Name & " " & DateString
Else
    FolderName = sItem & "\" & xWb.Name & " " & DateString 'Add a Backslash
End If