panchitocarioca
Registered User.
- Local time
- Today, 14:15
- Joined
- Aug 11, 2008
- Messages
- 11
Hi,
I have a small question.
In Access I have created a function that copies all (filtered) records of a form (in datasheet view) to a newly created Excel file.
At home this function / datanase works fine. When I tried to run it at work today, it did not work. I get the following error “Error 9 Subscript Out Of Range“. I googled this error and looked in forums to try to get an idea of what it is and how to resolve this, but I could not find any clear lead. It seems to be a “very general” error that could have a wide range of causes.
I have included the code of the function below this message. Does anybody have an idea what the problem is?
In case you do not know how to resolve this, but you do know another method of copying data of all shown records of a form in datasheet view into a new excel file, then I would very much appreciate it if you could explain it to me.
PS The records in the form can be filtered by using the filter command buttons of Access, only the filtered records should be copied (so exporting the query on which the form is based is not the solution as this will include the non-filtered records as well). In addition, I only want the columns which are shown in the datasheet form to be copied (depending on the situation, some columns are hidden in the form datasheet, which in such case should also not be copied into Excel. All this works fine with below code, apart from the strange error 9 problem at work.
Many thanks in advance for the help!
Best regards,
Ronald
Public Function CopyToExcel()
On Error GoTo err_handler
Dim ApXL As Object
Dim xlWBk As Object
Dim xlWSh As Object
DoCmd.SelectObject acForm, "Frm1"
DoCmd.RunCommand acCmdSelectAllRecords
DoCmd.RunCommand acCmdCopy
Set ApXL = CreateObject("Excel.Application")
Set xlWBk = ApXL.Workbooks.Add
ApXL.Visible = True
Set xlWSh = xlWBk.Worksheets("Sheet1")
ApXL.ActiveWorkbook.ActiveSheet.Range("A1").PasteSpecial Paste:=xlPasteValues
' selects all of the cells
ApXL.ActiveSheet.Cells.Select
' does the "autofit" for all columns
ApXL.ActiveSheet.Cells.EntireColumn.AutoFit
' selects the first cell to unselect all cells
xlWSh.Range("A1:A1").Select
einde:
Exit Function
err_handler:
DoCmd.SetWarnings True
MsgBox Err.Description, vbExclamation, Err.Number
Exit Function
End Function