r/vba•
razbarry33

Run-time error 9 when trying to reference workbook received from fileDialog

I have a method which lets the user pick the Excel file to export Access tables to. I get an error when I try to reference the workbook to clear the worksheets being exported to. The cells need to be cleared to avoid issues when trying to export to a sheet with content in it. I take the string from the filedialog and only take the file name and extension to reference the workbook. I have tried this with the workbook open and closed, but to no avail. The file name matches exactly so I actually have no idea why it work find it.

Private Sub ExportTables()

    Dim strFileName As String
    Dim fDialog As FileDialog
    Dim varFile As Variant
    
    Set fDialog = Application.FileDialog(msoFileDialogFilePicker)
    
    With fDialog
        
        'Title
        .Title = "Export to Excel File"
        
        'File type
        .Filters.Clear
        .Filters.Add "Excel Workbook", "*.xlsx, *.xlsm"
        
        'If Yes
        If .Show = True Then
            .AllowMultiSelect = False
            For Each varFile In .SelectedItems
                strFileName = Mid(varFile, InStrRev(varFile, "\") + 1)
                
                'Error Here
                Workbooks(strFileName).Worksheets("Table1").Cells.Clear
                
                If IsWorkBookOpen(CStr(varFile)) Then
                    Workbooks(strFileName).Close SaveChanges:=True
                End If
                
                'Export Tables
                DoCmd.TransferSpreadsheet acExport, 10, "Table1", varFile

            Next varFile
            MsgBox "Export complete."
        Else
        
        MsgBox "Excel export cancelled."

        End If

    End With
End Sub

Posted Jul 31, 2017, 2:28 PM UTC

111
Loading comments…