I am getting error Run-time error 3125 'Import$' is not a valid name. Make sure that it does not include invalid characters or punctuation and that it is not too long when I am attempting to import an Excel file to an Access Table. I only receive this error when other Excel files are open otherwise the Excel file is loaded to the table as expected. Here is some of the code I am working with:
Dim f As FileDialog, str As String
Set f = Application.FileDialog(msoFileDialogFilePicker)
f.Show
On Error GoTo Err1
str = f.SelectedItems(1)
Dim xl As Excel.Application
Set xl = New Excel.Application
xl.Visible = True
Dim xlWB As Excel.Workbook
Set xlWB = xl.Workbooks.Open(str)
'manipulate Excel file
'load spreadsheet
On Error GoTo Err2
DoCmd.TransferSpreadsheet acImport, 8, "JobCode", str, True, "Import!"
I originally thought and tried to change the filename, but was unsuccessful. It seems like the code is opening a new version of the import Excel file as Read-Only which might be confusing the Access database on which worksheet to import. But I am not sure why it's doing this and also why it only does this when another Excel file is open. Is this the problem? Does anyone know how to fix this?
Thank you!
Related
I'm using VB to open an excel file and I'm having trouble with encoding. Some characters are displayed as garbage. I discovered that when I open the file with excel then reopen it with utf8 encoding the characters display correctly. In my VB program when I try to use the reloadas method the reload appears to work but receive the error "object disconnected from it's clients" error message.
Is there a way I can avoid using the reloadas and open the file using utf8? If not how can resolve the error I'm getting?
Dim xlWorkbook As Excel.Workbook = xlapp.Workbooks.Open(SaveFN)
xlWorkbook.WebOptions.Encoding = Microsoft.Office.Core.MsoEncoding.msoEncodingUTF8
xlWorkbook.ReloadAs(Microsoft.Office.Core.MsoEncoding.msoEncodingUTF8)
Dim xlWorkSheet As Excel.Worksheet = xlWorkbook.Worksheets(1) 'error occurs here
thanks.
when I try to use the reloadas method the reload appears to work but
receive the error "object disconnected from it's clients" error
message.
This is because when the Excel reloads the Workbook, the existing Workbook object is destroyed and the reference held by xlWorkbook is no longer valid.
Based on the usage of WebOptions, the file is probably an Html file. However, Excel does not expose an open method that takes a file format argument. This leaves using Application.ActiveWorkBook or Application.WorkBooks collection as the only means to retrieve a reference to retrieve the Workbook.
Dim xlWorkbook As Excel.Workbook = xlapp.Workbooks.Open(SaveFN)
xlWorkbook.WebOptions.Encoding = Microsoft.Office.Core.MsoEncoding.msoEncodingUTF8
xlWorkbook.ReloadAs(Microsoft.Office.Core.MsoEncoding.msoEncodingUTF8)
xlWorkbook = xlapp.ActiveWorkbook ' *** add this statement
Dim xlWorkSheet As Excel.Worksheet = xlWorkbook.Worksheets(1)
I have a downloaded CSV file that I am trying to open and then save as an .xlsx file using code. I am very very new to VB, and have just modified code that I have found to make things work. Yesterday the code worked great, but today it stalls out on the "wb.SaveAs" line. The odd thing about the error is that the file actually saved to the folder. Any help would be appreciated.
Public Function Upload_New_Orders_Excel()
'the path to the excel workbook
Dim XcelFile As Excel.Application
Dim wb As Excel.Workbook
Dim strExcelPath As String
Set XcelFile = New Excel.Application
Set wb = XcelFile.Workbooks.Open("C:\Users\mpdav\downloads\orders_export_1.csv")
wb.SaveAs FileName:="C:\Users\mpdav\OneDrive\Documents\R&M Hospitality\At Your Door\Daily Reports\orders_export_1.xlsx", FileFormat:=51
wb.Close
Set XcelFile = Nothing
Kill "C:\Users\mpdav\downloads\orders_export_1.csv"
strExcelPath = "C:\Users\mpdav\OneDrive\Documents\R&M Hospitality\At Your Door\Daily Reports\orders_export_1.xlsx"
'import data from excel
Call DoCmd.TransferSpreadsheet(acImport, acSpreadsheetTypeExcel8, "temp_tbl_orders_export", "C:\Users\mpdav\OneDrive\Documents\R&M Hospitality\At Your Door\Daily Reports\orders_export_1.xlsx", True, "A1:BP1000")
Kill "C:\Users\mpdav\OneDrive\Documents\R&M Hospitality\At Your Door\Daily Reports\orders_export_1.xlsx"
End Function
I have a PowerPoint macro that should open an Excel file.
Public Sub SortList()
Dim MyFile as String
Dim xlApp as Object
Dim xlWorkBook as Object
Set xlApp = CreateObject("Excel.Application")
With Application.FileDialog(msoFileDialogOpen)
.AllowMultiSelect = False
.Show
MyFile = SelectedItems(1)
End With
xlApp.Visible = True
xlApp.Workbooks.Open MyFile
Set xlWorkBook = xlApp.Workbooks.Open(MyFile)
This code was previously working with no errors. However, I have started receiving the error message
"Run-time error '-2147467259 (80004005)': Method 'Open' of object 'Workbooks' failed."
The error occurs when trying to run the "Set" line of code.
The issue is that I can see that the code is successfully opening the Excel file!
Things I have tried (in about every possible combination):
-Changing the code to this (I thought maybe the program was trying to open the file twice):
xlApp.Visible = True
Set xlWorkBook = xlApp.Workbooks.Open(MyFile)
-Adding ReadOnly:= True to both or either .Open command, at one point this gave me an "Automation error- unspecified error" message which I have never seen before...
-Changing the Set line to this (and variations thereof):
xlApp.Workbooks.Open MyFile
Set xlWorkBook = xlApp.Workbooks(Dir(MyFile))
-Ensuring Excel is completely closed prior to running the code
The frustrating aspect is that this code worked perfectly last week, so I'm also at a loss as to why it would suddenly stop working. Any assistance would be greatly appreciated.
Workbooks.Open can cause issues if you call it on an already open workbook.
So, don't open twice. Remove the following line:
xlApp.Workbooks.Open MyFile
I am currently trying to use an access database which uses vba to generate Excel spreadsheets and AutoCAD drawings; I didn't write the code, and I don't have experience coding in this language. When generating an excel file, the code gets to the line MyXL.Parent.Windows(1).Visible = True, it gives the error. The excel file is generated, but is identical to the template.
The File and directory names are placeholders
Dim MyXL As Object
FileCopy "\Directory\Template", "\Directory\Filename"
' This copies an Excel file, first half, then renames it with the Sales order number
Set MyXL = GetObject("\Directory\Template")
' This opens the Excel file named in the upper code second half
MyXL.Application.Visible = True
MyXL.Application.WindowState = 3
' MyXL1.Activate
MyXL.Parent.Windows(1).Visible = True
MyXL.Parent.ActiveWindow.WindowState = 2
With MyXL.Worksheets(1)
End With
At this point it sets a lot of values (I assume) in the form .Range("T60").Value = Me![Text516]
MyXL.Worksheets(1).Activate
MyXL.Save
MyXL.Parent.Quit ' This is what you have to do to close the Application
'MyXL.Parent.Quit
' MyXL.Parent.ActiveWindow.WindowState = xlMinimized
' MyXL.Close
The possible duplicate relates to copying an excel spreadsheet, however this problem goes further than that
Edit: I made a mistake and previously had the line Set MyXL = GetObject("\SameDirectory\SameFilename") but it is actually Set MyXL = GetObject("\Directory\Template")
Example of working code to open an Excel workbook, edit, save to a new name.
Sub CopyExcel()
Dim xl As Excel.Application, xlw As Excel.Workbook
Set xl = CreateObject("Excel.Application")
'the following two lines have same result
Set xlw = xl.Workbooks.Open("C:\Users\June\MyStuff\Condos.xlsx", , True)
'Set xlw1 = xl.Workbooks.Add("C:\Users\June\MyStuff\Condos.xlsx")
'code to edit
xlw.SaveAs "C:\Users\June\MyStuff\Condos2.xlsx"
xl.Quit
End Sub
What's the "best" way to read (just read) an Excel file from within an Access 2007 application. I only want to loop trough the rows and put the data into an Access table.
I don't want a manually import (Get External Data dialog) but by VBA. The user gets a Form with a Browse button and then points to a Excel file with a defined content/format. After that the VBA code reads the data and puts it into the Access database.
You could try the DoCmd.TransferSpreadsheet method.
DoCmd.TransferSpreadsheet acImport, , "from_excel","C:\Access\demo.xls", True
That imports spreadsheet data into a table named from_excel, and assumes the first row of the spreadsheet contains field names. See Access help for TransferSpreadsheet or online here, for more details.
If you want to read the entire spreadsheet in, you can import an Excel spreadsheet directly into Access. See here or here.
You can also choose to link to the Excel spreadsheet instead of importing it. That way any changes to the Excel spreadsheet will be reflected in the linked table. However, you won't be able to make changes from within Access.
A third option is to write some VBA code within Access to open a recordset and read the spreadsheet in. See the answers from KeithG in this thread. You can do something like this to open the spreadsheet in VBA:
Dim xl As Excel.Application
Dim xlsht As Excel.Worksheet
Dim xlWrkBk As Excel.Workbook
Set xl = CreateObject("Excel.Application")
Set xlWrkBk = GetObject("H:/ggg.xls")
Set xlsht = xlWrkBk.Worksheets(1)
Try something like this:
Dim excelApp As Excel.Application
Dim workbook As Excel.Workbook
Dim worksheet As Excel.Worksheet
Set excelApp = CreateObject("Excel.application")
Set workbook = excelApp.Open("C:\someFileName.xls")
Set worksheet = workbook.Worksheets(1)
And then loop through the rows and columns, pull the data from the cells, and insert it into the database. (You can use the worksheet.cells method.) Try searching on google for code samples.
Hereafter my method to read an excel file and all the worksheet names:
Function listOfWorksheet(filename As String) As Collection
Set dbExcel = OpenDatabase(filename, False, True, "excel 8.0")
For Each TableDef In dbExcel.TableDefs
Debug.Print TableDef.Name
Next
End Function
Now, you can use the name of the worksheet to read the whole content:
Function ReadMyObjects(filename as String, wsName as String) As Collection
On Error GoTo label_error
Set results = New Collection
Dim countRows As Integer
Set dbExcel = OpenDatabase(filename, False, True, "excel 8.0")
Set excelRs = dbExcel.OpenRecordset(wsName, dbOpenSnapshot)
Do While Not excelRs.EOF
'Data Rows
Dim item As MyObject 'a custom object defined by you.
Set item = New MyObject
item.ABC = Nz(excelRs.Fields("COLUMN_ABC").Value, "")
item.DEF = Nz(excelRs.Fields("COLUMN_DEF").Value, "")
results.Add item
excelRs.MoveNext
Loop
excelRs.Close
Set ReadMyObjects= results
GoTo label_exit
label_error:
MsgBox "ReadMyObjects" & Err.Number & " " & Err.Description
label_exit:
End Function