Share via

Excel file does not close after import into Access using VBA

Anonymous
2021-11-18T19:52:05+00:00

Hello, I have an Access application where I open an Excel file, select a sheet and import the data. However, the problem is that if there is another Excel file open, the imported file does not close automatically and a "read-only" dialog opens for the Excel file I imported, halting import process. I have two sets of code, one with functions in a module and the other code within the form that will import the Excel File.

1. Function Code in Module.

Option Compare Database

Dim m_OpenExcel As Excel.Application

Dim m_OpenWorkbook As Workbook

Public Function GetExcelFile()

Set fDialog = Application.FileDialog(3) 

With fDialog 

    ' Allow user to make multiple selections in dialog box 

    .AllowMultiSelect = False 

    ' Set the title of the dialog box. 

    .Title = "Please select Excel file to import" 

    ' Clear out the current filters, and add our own. 

    .Filters.Clear 

    .Filters.Add "Excel 2007", "\*.xls\*" 

    ' Show the dialog box. If the .Show method returns True, the user picked a 

    ' file. If the .Show method returns False, the user clicked Cancel. ' 

    If .Show = True Then 

        GetExcelFile = .SelectedItems(1) 

    Else 

        GetExcelFile = Null 

    End If 

End With 

End Function

Public Function OpenExcelWorkbook(path As String)

If m\_OpenExcel Is Nothing Then 

    Set m\_OpenExcel = New Excel.Application 'CreateObject("Excel.Application") 

End If 

If IsEmpty(m\_OpenWorkbook) Then 

    m\_OpenExcel.Workbooks.Open path 

    Set m\_OpenWorkbook = m\_OpenExcel.ActiveWorkbook 

ElseIf m\_OpenWorkbook Is Nothing Then 

    m\_OpenExcel.Workbooks.Open path 

    Set m\_OpenWorkbook = m\_OpenExcel.ActiveWorkbook 

ElseIf m\_OpenWorkbook.FullName <> path Then 

    m\_OpenExcel.Workbooks.Open path 

    Set m\_OpenWorkbook = m\_OpenExcel.ActiveWorkbook 

End If 

End Function

Public Function ExcelSheetsNameList(path As String) As String()

OpenExcelWorkbook (path) 

Dim shts() As String 

ReDim shts(m\_OpenWorkbook.Sheets.Count - 1) 

For x = 1 To m\_OpenWorkbook.Sheets.Count 

    shts(x - 1) = m\_OpenWorkbook.Sheets(x).name 

Next x 

ExcelSheetsNameList = shts 

End Function

Public Function GetExcelWorksheet(path As String, sheetName As String) As Worksheet

OpenExcelWorkbook (path) 

Set GetExcelWorksheet = m\_OpenWorkbook.Sheets(sheetName) 

End Function

Public Sub DeleteTableSafe(name As String)

On Error Resume Next 

DoCmd.DeleteObject acTable, name 

Exit Sub 

Error:

MsgBox Err.Description, vbInformation, "Error No: " & Err.Number 

End Sub

Public Sub NewImportUtilitiesModuleDispose()

If Not m\_OpenWorkbook Is Nothing Then 

    m\_OpenWorkbook.Close 

    Set m\_OpenWorkbook = Nothing 

End If 

If Not m\_OpenExcel Is Nothing Then 

    m\_OpenExcel.Quit 

    Set m\_OpenExcel = Nothing 

End If 

End Sub

2. Code in Form

Option Compare Database

Private Sub buttonBrowse_Click()

'The first requirement is to be able to browse to the Excel file. Here is the code that is executed in the form when the “Browse” button is clicked: 

'This code first clears out information in the form that may be applicable to the last file that was selected, and then the user is provided a dialog to select a file with the “xlsx” extension. If a file is not selected, then the code returns, otherwise the Excel file is opened to find its sheet names, which are displayed in a list box to allow the user to select the sheet to import. 

'First the information in the Form is cleared, including clearing out the file name TextBox, the sheet names ListBox, and the hide the sub form. 

'Clear out existing information before browse 

Dim itemsString As String 

textboxExcelFileToImport = "" 

listBoxWorksheets.RowSource = "" 

subFormData.Visible = False 

DoEvents 

'Allow user to browse Excel file to import 

textboxExcelFileToImport = GetExcelFile 

If IsNull(textboxExcelFileToImport) Then Exit Sub 

'Fill in list box that will contain the sheet names 

itemsString = Join(ExcelSheetsNameList(textboxExcelFileToImport), ";") 

listBoxWorksheets.RowSource = itemsString 

End Sub

Private Sub buttonImportBudgetandActuals_Click()

Dim response As VbMsgBoxResult

If subFormData.Visible = False Then

MsgBox ("No Data to Import. Please select file and sheet to be imported")

Else

DoCmd.SetWarnings False 'Stop the warning message that asks you if you are sure you want to continue

DoCmd.OpenQuery ("qry_Importbudgetandactuals") ' Make table from Temp table of Imported Records

Call delTbl 'delete the Excel$ error tables

DoCmd.SetWarnings True

response = MsgBox("Budget and Actuals Records have been imported, do you want to Close form?", vbQuestion + vbYesNo)

If response = vbYes Then

  DoCmd.Close acForm, "Frm\_ImportActuals" 

End If

End If

End Sub

Private Sub Form_Close()

NewImportUtilitiesModuleDispose

End Sub

Private Sub Form_Load()

textboxExcelFileToImport = "" 

listBoxWorksheets.RowSource = "" 

subFormData.Visible = False 

    'DeleteTableSafe "T\_Temp" 

End Sub

Private Sub listBoxWorksheets_Click()

Dim sheet As Worksheet 

Dim sheetRange As String 

subFormData.SourceObject = Empty 

DeleteTableSafe "T\_Temp" 

DoEvents 

Set sheet = GetExcelWorksheet(textboxExcelFileToImport, listBoxWorksheets) 

    sheetRange = listBoxWorksheets & "!" 'this code will import all the columns on the spreadsheet 

    DoCmd.TransferSpreadsheet acImport, acSpreadsheetTypeExcel12, "T\_Temp", textboxExcelFileToImport, True, sheetRange 

    subFormData.SourceObject = "Table.T\_Temp" 

    subFormData.Visible = True 

Set sheet = Nothing 

End Sub

Microsoft 365 and Office | Access | Other | Windows

Locked Question. This question was migrated from the Microsoft Support Community. You can vote on whether it's helpful, but you can't add comments or replies or follow the question.

0 comments No comments

Answer accepted by question author

Anonymous
2021-11-19T21:04:13+00:00

Please mark this as resolved.

Was this answer helpful?

1 person found this answer helpful.
0 comments No comments

8 additional answers

Sort by: Most helpful
  1. Anonymous
    2021-11-19T20:25:03+00:00

    OK, I don't use Excel that much so I was unaware if Excel was already open, TransferSpreadsheet would open the worksheet.

    If there are multiple ranges and you need your code to get the ranges before running TransferSpreadsheet. Then the only alternative I see is to make sure all wiorksheets are closed before you start the process. This code should do that:

    Set ObjXL = GetObject(, "Excel.Application")
    do until ObjXL Is Nothing
            Debug.Print "Closing XL"
            ObjXL.Application.DisplayAlerts = False
            ObjXL.Workbooks.Close
            ObjXL.Quit
            Set ObjXL = Nothing
            Set ObjXL = GetObject(, "Excel.Application")  ' important!
    loop
    

    Was this answer helpful?

    1 person found this answer helpful.
    0 comments No comments
  2. Anonymous
    2021-11-18T22:36:08+00:00

    Yes, That's what I explained. Whenever I am importing data from Excel I generally use TransferSpreadsheet to Link to tyhe table, then run an Append query to add it to the Access table.

    Again, When you use TransferSpreadsheet, there is NO reason to open the Excel file.

    Was this answer helpful?

    0 comments No comments
  3. Anonymous
    2021-11-18T22:31:54+00:00

    Hi Julie, I'll try to help.

    So, you are using Transfer Spreadsheet to get the Excel table. Why are you then opening the Excel file? TransferSpreadsheet will import the range without opening the Excel file!

    Also, why IMPORT the file? You should be linking to the file, since you run an Import query that appends the data from your Temp table into your Access table. So I see no reason to open Excel or to import the data,

    Just using TransferSpreadsheet without opening the Excel file should solve your problem.

    If you need further clarification on this feel free to ask.

    Hi Scott, thank you for taking the time to review my question.

    So, you are using Transfer Spreadsheet to get the Excel table. Why are you then opening the Excel file? TransferSpreadsheet will import the range without opening the Excel file! It is my understanding that using the TransferSpreadsheet alone will not populate the file picker or make the sheets visible to the user. I wanted to give the user the ability to visualize the data before importing it into the Database.

    Also, why IMPORT the file? You should be linking to the file, since you run an Import query that appends the data from your Temp table into your Access table. So I see no reason to open Excel or to import the data, I will distribute this tool to a few users so that they are able to import 2 different sets of data and combine them. These users, however, may not be importing data for the same period. For example, one user could import the data for 3 months while another user could be importing data for 4 months. Every time they import new data, the old data will be overwritten. Not to mention that they may change the original file name.

    Do you think I can use another alternative?

    Was this answer helpful?

    0 comments No comments
  4. Anonymous
    2021-11-18T20:40:27+00:00

    Hi Julie, I'll try to help.

    So, you are using Transfer Spreadsheet to get the Excel table. Why are you then opening the Excel file? TransferSpreadsheet will import the range without opening the Excel file!

    Also, why IMPORT the file? You should be linking to the file, since you run an Import query that appends the data from your Temp table into your Access table. So I see no reason to open Excel or to import the data,

    Just using TransferSpreadsheet without opening the Excel file should solve your problem.

    If you need further clarification on this feel free to ask.

    Was this answer helpful?

    0 comments No comments