In VBA, how does one make a table from a recordset - ms-access

I have a recordset that I want to export into Excel 2000 format (acSpreadsheetTypeExcel9). I believe I need to drop it into a table first then execute a DoCmd.TransferSpreadsheet (keeps it easy and it works). The user sets just a few parameters in the form, thus the Me. syntax you will see.
Here's the working code so far:
Select Case Me.Controls("frame_ChooseReport").Value
Case 1
sExecuteQuery = "qry_PDSR w/ Destruct Dates"
bHasProgramCode = True
sFileName = "Project_Doc_Submittal_Request_better"
Case 2
sExecuteQuery = "qry_PDSR w/Destruct Dates BE"
bHasProgramCode = False 'This is the only query here that doesn't have a Program Code parameter
sFileName = "Project_Doc_Submittal_Request_better_BE"
Case 3
sExecuteQuery = "qry_Project Documentation Submittal Request w/ Destruct Dates"
bHasProgramCode = True
sFileName = "Project_Doc_Submittal_Request_ENH"
Case 4
sExecuteQuery = "qry_Project_Doc_Submittal_Request_w_Destruct_Dates_HES_Installer"
bHasProgramCode = True
sFileName = "Project_Doc_Submittal_Request_Installer"
Case Else
Stop 'Error! This should never be reached!
End Select
'Execute query & save output to Excel
Set qdf = CurrentDb.QueryDefs(sExecuteQuery) 'Open the query
'Assign values to the query using the parameters option
If bHasProgramCode = True Then
qdf.Parameters(0) = Me.lbl_ProgramCodes.Section
qdf.Parameters(1) = Me.txt_StartDate
qdf.Parameters(2) = Me.txt_EndDate
Else
qdf.Parameters(0) = Me.txt_StartDate
qdf.Parameters(1) = Me.txt_EndDate
End If
sFullPath = Me.lbl_SaveTo.Caption & "\" & sFileName
Set rst = qdf.OpenRecordset 'Convert the querydef to a recordset and run it
If rst.BOF = True And rst.EOF = True Then
MsgBox "No records were found.", vbExclamation, "Empty recordset"
Exit Sub
End If
'Dump recordset into a table, export it to Excel, then delete it.
'Here is where the recordset needs to become a table.
DoCmd.TransferSpreadsheet acExport, acSpreadsheetTypeExcel9, "qry_PDSR w/ Destruct Dates", sFullPath, True 'Export table to an Excel format
'Clean up!
DoCmd.DeleteObject acTable, gTEMP_TBL 'Done with the temporary table so delete it
rst.Close
qdf.Close
Set rst = Nothing
Set qdf = Nothing
Help/suggestions? Thank you.
Access 2010 in Windows 7
---------- FOLLOW UP ----------
Here's the query I added that will use the references of the opened form per Remou's suggestion:
SELECT dbo_PROJECT.PROJECTID, dbo_PROJECT.TITLE, dbo_PROJECT.PROGRAMCODE, dbo_PROJECT.PROJECTTYPE, dbo_PROJECT.REFERENCE, dbo_PROJECT.STATUS, dbo_PROJECT.PMC, dbo_TRANSACTION_SUM.STATUS, dbo_TRANSACTION_SUM.IMPORTEDDT, dbo_TRANSACTION_SUM.CHECKDT, dbo_PROJECT.NOTES, dbo_TRANSACTION_SUM.TRANSACTIONID, dbo_TRANSACTION_SUM.GL_ACCT, dbo_PROJECT_SUM.PAID_INCENT_TOTAL, dbo_TRANSACTION_SUM.AMOUNT
FROM ((dbo_INCENTIVE RIGHT JOIN dbo_PROJECT ON dbo_INCENTIVE.PROJECTID = dbo_PROJECT.PROJECTID) LEFT JOIN dbo_TRANSACTION_SUM ON dbo_INCENTIVE.INCENTIVEID = dbo_TRANSACTION_SUM.INCENTIVEID) LEFT JOIN dbo_PROJECT_SUM ON dbo_PROJECT.PROJECTID = dbo_PROJECT_SUM.PROJECTID
WHERE (((dbo_PROJECT.PROGRAMCODE) In ([Forms]![Submittal_Request_Report]![txt_ListProgramCodeSelections])) AND ((dbo_TRANSACTION_SUM.CHECKDT) Between [Forms]![Submittal_Request_Report]![txt_StartDate] And [Forms]![Submittal_Request_Report]![txt_EndDate]));
Here's the routine that is in the On_Exit event of the listbox:
Private Sub list_ProgramCodes_Exit(Cancel As Integer)
'Get selection from Program Code listbox and store it in a hidden textbox for the query.
Dim x As Long, sValue As String, ctlSource As Control
sValue = ""
Set ctlSource = Me!list_ProgramCodes
For x = 0 To ctlSource.ListCount - 1
If ctlSource.Selected(x) Then
sValue = sValue & ctlSource.Column(0, x) & ","
End If
Next
Me.txt_ListProgramCodeSelections.Value = Left(sValue, Len(sValue) - 1) 'Drop the last comma
Set ctlSource = Nothing
End Sub
Works great! The SQL line In ([Forms]![Submittal_Request_Report]![txt_ListProgramCodeSelections]) pulls the list of items in the hidden textbox (using a label didn't work) that was populated with the selection from the listbox on the form.
This is now the code for exporting the query:
Private Sub btn_RunReport_Click()
Dim sExecuteQuery As String, sFullPath As String, sFileName As String
On Error GoTo Err_btn_RunReport_Click
If Left(Me.lbl_SaveTo.Caption, 4) = "save" Then
MsgBox "Please select a folder to save the results to.", vbInformation, "No folder selected"
Exit Sub
End If
Select Case Me.Controls("frame_ChooseReport").Value
Case 1
sExecuteQuery = "qry_PDSR_Destruct_Dates_form"
sFileName = "Project_Doc_Submittal_Request.xls"
Case 2
sExecuteQuery = "qry_Project_Doc_Submittal Request w/ Destruct Dates_form"
sFileName = "Project_Doc_Submittal_Request_ENH.xls"
Case 3
sExecuteQuery = "qry_PDSR_w_Destruct_Dates_HES_Installer_form"
sFileName = "Project_Doc_Submittal_Request_Installer.xls"
Case Else
Stop 'Error! This should never be reached!
End Select
sFullPath = Me.lbl_SaveTo.Caption & "\" & sFileName
DoCmd.TransferSpreadsheet acExport, acSpreadsheetTypeExcel9, sExecuteQuery, sFullPath, True 'Export table to an Excel format
Exit_btn_RunReport_Click:
Exit Sub
Err_btn_RunReport_Click:
MsgBox Err.Description
Resume Exit_btn_RunReport_Click
End Sub
Thanks Remou!

I suggest you just set the sql of a query to a suitable string and then export the query:
sSQL="SELECT * FROM Table WHERE Field=" & me.MyText
If IsNull(DLookup("name", "msysobjects", "name='query1'")) Then
CurrentDb.CreateQueryDef "Query1", sSQL
Else
CurrentDB.QueryDefs("Query1").SQL = sSQL
End If
DoCmd.TransferSpreadsheet acExport, acSpreadsheetTypeExcel9, "Query1", sFullPath
You can create a query that references an open form:
SELECT Test.ID, Test.Data
FROM Test
WHERE Test.AField=[forms]![test]![pickone]

Related

MS access VBA code for Excel file leaves it locked open [duplicate]

I've been running into issues with this code. It works fine if I restart the computer and run it, but once the code has been run once it starts to cause errors. I will either get either the "save error" or the "admin error" because the file (either the original or the other) is un-accessible. I can sometimes close down background excel programs from the task-manager to fix it (but not always)
The code's purpose is to download an excel sheet off the internet and add the new rows (and update the old rows) to an ms-access Database.
Whats peculiar is I haven't been able to see any trend with the logical errors.
Const localSaveLocation = ########
Const NetworkDSRTLocation = ########
Private Sub download_btn_Click()
Dim xlsApp As Excel.Application
Dim xlsBook As Excel.Workbook
Dim xlsSheet As Excel.Worksheet
On Error GoTo adminError
Set xlsBook = Workbooks.Open(NetworkDSRTLocation)
Set xlsApp = xlsBook.Parent
On Error GoTo 0
' go to the ERS tab of the workbook, delete the first 3 rows
Worksheets("ERS").Select
Set xlsSheet = xlsBook.Worksheets("ERS")
For row_ctr = 1 To 3
xlsSheet.Rows(1).EntireRow.Delete
Next row_ctr
'set up 'ERS' named range for all cells in this worksheet
xlsSheet.UsedRange.Select
col_count = Cells(1, Columns.Count).end(xlToLeft).Column
row_count = (xlsSheet.Cells(Rows.Count, 1).end(xlUp).Row) + 1
ActiveWorkbook.Names.Add name:="ERS", RefersToR1C1:="=ERS!R1C1:R" & row_count & "C" & col_count
On Error GoTo saveError
Kill localSaveLocation
xlsBook.SaveAs FileName:=localSaveLocation
xlsApp.Quit
On Error GoTo 0
DoCmd.TransferSpreadsheet acImport, acSpreadsheetTypeExcel12, "DSRT_TEMP", localSaveLocation, True, "ERS"
numOfChangesDSRT = DCount("ID", "changed_records")
DoCmd.RunSQL "update ers_local inner join changed_records on changed_records.id = ers_local.id Set last_updated = Date();"
DoCmd.RunSQL "update ers_local inner join dsrt_temp on dsrt_temp.id = ers_local.id Set source = 'DSRT';"
DoCmd.RunSQL "DELETE FROM [dsrt_ers] WHERE dsrt_ers.id in (select id from ers_local where source = 'DSRT');"
DoCmd.RunSQL "INSERT INTO DSRT_ERS SELECT * FROM DSRT_TEMP"
DoCmd.RunSQL "DROP TABLE DSRT_TEMP;"
xlsApp.Quit
DoCmd.Requery
DoCmd.Hourglass False
Exit Sub
adminError:
DoCmd.Hourglass False
Exit Sub
saveError:
DoCmd.Hourglass False
On Error Resume Next
xlsApp.Quit
Exit Sub
End Sub
Be very careful opening and closing the Excel objects correctly:
Const localSaveLocation = ########
Const NetworkDSRTLocation = ########
Private Sub download_btn_Click()
Dim xlsApp As Excel.Application
Dim xlsBook As Excel.Workbook
Dim xlsSheet As Excel.Worksheet
Set xlsApp = New Excel.Application
Set xlsBook = xlsApp.Workbooks.Open(NetworkDSRTLocation)
' Go to the ERS tab of the workbook, delete the first 3 rows.
Set xlsSheet = xlsBook.Worksheets("ERS")
For row_ctr = 1 To 3
xlsSheet.Rows(1).EntireRow.Delete
Next row_ctr
' Set up 'ERS' named range for all cells in this worksheet.
xlsSheet.UsedRange.Select
col_count = xlsSheet.Cells(1, Columns.Count).end(xlToLeft).Column
row_count = (xlsSheet.Cells(Rows.Count, 1).end(xlUp).Row) + 1
xlsBook.Names.Add name:="ERS", RefersToR1C1:="=ERS!R1C1:R" & row_count & "C" & col_count
If Dir(localSaveLocation, vbNormal) <> "" Then
Kill localSaveLocation
End If
xlsBook.SaveAs FileName:=localSaveLocation
Set xlsSheet = Nothing
xlsBook.Close
Set xlsBook = Nothing
xlsApp.Quit
Set xlsApp = Nothing
DoCmd.TransferSpreadsheet acImport, acSpreadsheetTypeExcel12, "DSRT_TEMP", localSaveLocation, True, "ERS"
numOfChangesDSRT = DCount("ID", "changed_records")
DoCmd.RunSQL "update ers_local inner join changed_records on changed_records.id = ers_local.id Set last_updated = Date();"
DoCmd.RunSQL "update ers_local inner join dsrt_temp on dsrt_temp.id = ers_local.id Set source = 'DSRT';"
DoCmd.RunSQL "DELETE FROM [dsrt_ers] WHERE dsrt_ers.id in (select id from ers_local where source = 'DSRT');"
DoCmd.RunSQL "INSERT INTO DSRT_ERS SELECT * FROM DSRT_TEMP"
DoCmd.RunSQL "DROP TABLE DSRT_TEMP;"
DoCmd.Requery
DoCmd.Hourglass False
End Sub

Access error: can not add records joint key of table 'TableName' not in recordset

I have two linked Tables 'tblPatients' and 'tblDSA' and two continues forms 'frmPatients' and 'frmDSA'. When I create a new patient via 'frmPatient'I would like to add a new record for that patient in 'frmDSA' without closing the form.
On 'frmPatients' next to each record there is a button 'SaveNewRecord' that does the following:
(1)saves a new record to 'tblPatients' and also filters
(2) opens 'frmDSA' to display related records to that Patients.
Here is the filtering code:
If Not Me.NewRecord Then
DoCmd.OpenForm "DSAfrm", _
WhereCondition:="LABCODE=" & Me.LABCODE
End If
Here is what happens:
After the 'DSAfrm' pops up and I try to enter a new record I get the following error."can not add records joint key of table 'TableName' not in record-set"
The new patient has been save to 'tblPatients' but Access is not letting me add any new records. Please help!
Here is the code that I use to save the new records:
Private Sub Command385_Click()
Dim db As DAO.Database
Dim PatientTable As DAO.Recordset
Dim DSAtable As DAO.Recordset2
Dim errMsg As String 'Where we will store error messages
Dim errData As Boolean 'Default = False if we have an error we will set it to True.
Dim i As Integer 'used as a counter in For..Next loops.
Dim x As Integer 'used as counter in For..Next loops.
Dim errorArray(0 To 3) As String 'Array to hold the error messages so we can 'use them if needed.
If Me.LABCODE.Value = "" Then
errorArray(0) = "Must Enter Labcode."
errData = True
End If
If Me.LastName.Value = 0 Then
errorArray(1) = "Must Enter Patient Number"
errData = True
End If
If Me.FirstName.Value = "" Then
errorArray(2) = "Must Enter Insurance Type"
errData = True
End If
If Me.MRN.Value = "" Then
errorArray(3) = "Must Enter Intake Nurse"
errData = True
End If
'MsgBox "errData = " & errData
If errData = True Then
i = 0
x = 0
For i = 0 To 3
If errorArray(i) <> "" Then
If x > 0 Then
errMsg = errMsg & vbNewLine & errorArray(i)
Else
errMsg = errorArray(i)
x = x + 1
End If
End If
Next i
MsgBox errMsg & vbNewLine & "Please try again."
errMsg = ""
Me.LABCODE.SetFocus
Exit Sub
End If
Set db = CurrentDb()
Set PatientTable = db.OpenRecordset("tblPatients")
With PatientTable
.AddNew
!LABCODE = Me.LABCODE.Value
!LastName = Me.LastName.Value
!FirstName = Me.FirstName.Value
!MRN = Me.MRN.Value
!MRNTwo = Me.MRN2.Value
Debug.Print Me.MRN.Value
'!CPI#2 = Me.MRN2.Value
!Kidney = Me.cbKidney.Value
!Heart = Me.cbHeart.Value
!Lung = Me.cbLung.Value
!Liver = Me.cbLiver.Value
!Pancreas = Me.cbPancreas.Value
!DateLogged = Format(Date, "MM/DD/YY")
.Update
End With
'End If
Set DSAtable = db.OpenRecordset("tblDSA")
With DSAtable
.AddNew
!LABCODE = Me.LABCODE.Value
.Update
End With
'Let the user know it worked.
MsgBox "This patient has been added successfully.", vbOKOnly
'If Not Me.NewRecord Then
DoCmd.OpenForm "DSAfrm", _
WhereCondition:="LABCODE=" & Me.LABCODE
'End If
End Sub

MS Access Populate a form from pass-through query

I suspect this is a simple syntax issue, but I'm stuck.
I have this function:
Function CreateSPT(SPTQueryName As String, SQLString As String, _
ConnectString As String)
Dim mydatabase As Database, myquerydef As QueryDef, MyRS As Recordset
Set mydatabase = DBEngine.Workspaces(0).Databases(0)
Set myquerydef = mydatabase.CreateQueryDef(SPTQueryName)
myquerydef.Connect = ConnectString
myquerydef.SQL = SQLString
myquerydef.ReturnsRecords = False
myquerydef.ReturnsRecords = True
Set MyRS = myquerydef.OpenRecordset()
'MyRS.MoveFirst
DoCmd.OpenQuery SPTQueryName, acViewNormal, acReadOnly
myquerydef.Close End Function
When a button is pressed on my Form this is called.
Private Sub Btn_Search_Click()
If Not IsNull(DLookup("[AccessionNumber]", "[SA2001]", "[AccessionNumber] = '" & [Forms]![SA2001]![Txt_LabEpNo] & "'")) Then
'MsgBox "Found"
'Populates the form as required
'I've removed the code as it's messy
Else
'MsgBox "Not Found"
Me.Refresh
Dim SPTQueryName As String
Dim SQLString As String
Dim ConnectString As String
DoCmd.Close acQuery, "XQuery"
DoCmd.DeleteObject acQuery, "XQuery"
SPTQueryName = "XQuery"
SQLString = "SELECT SQLUser.EP_VisitNumber.EPVIS_DebtorNumber_DR as HospitalNumber, SQLUser.EP_VisitNumber.EPVIS_GivenName as Forename, SQLUser.EP_VisitNumber.EPVIS_Surname as Surname, SQLUser.EP_VisitNumber.EPVIS_DateOfBirth as DOB, SQLUser.EP_VisitNumber.EPVIS_DoctorCode_DR->CTDR_Surname as CONS, SQLUser.EP_VisitNumber.EPVIS_VisitNumber as AccessionNumber, SQLUser.EP_VisitNumber.EPVIS_DateOfCollection as SampleReceivedDate, SQLUser.EP_VisitTestSet.VISTS_TestSet_DR->CTTS_Department_DR->CTDEP_NAME as LabDept FROM SQLUser.EP_VisitTestSet, SQLUser.EP_VisitNumber WHERE ( SQLUser.EP_VisitTestSet.VISTS_ParRef=SQLUser.EP_VisitNumber.EPVIS_VisitNumber ) AND ( SQLUser.EP_VisitTestSet.VISTS_ParRef = '1500000000')"
ConnectString = "ODBC;DSN=DSNNAME;SERVER=IPADDRESS;PORT=1972;DATABASE=DATABASENAME;AUTHENTICATION METHOD=0;UID=USERNAME;PWD=PASSWORD;STATIC CURSORS=0;QUERY TIMEOUT=0;UNICODE SQLTYPES=0"
Call CreateSPT(SPTQueryName, SQLString, ConnectString)
'Me.[Hospital Number] = rec("HospitalNumber")
Me.Refresh
Me.[Hospital Number] = Null
Me.[Hospital Number] = MyRS("HospitalNumber")
End If End Sub
My issue is I cannot populate the form with the results of the pass-through query.
Essentially, how do I declare the recordset so I can populate the form as Me.[Hospital Number] = MyRS("HospitalNumber") does not work as "MyRS" is function not defined.
How do you have in mind these two statements should work together:
myquerydef.ReturnsRecords = False
Set MyRS = myquerydef.OpenRecordset()
You must have a query that returns records, then open a recordset from this, then pull a value from the recordset.
You declare MyRs in another function.
You must have something like:
MyRs = somequery.OpenRecordset()
Me![Hospital Number].Value = MyRs!HospitalNumber.Value

Recordcount returning too many records

Hello I have some vba code in a Form in MS Access 2013 and for some reason when I get a record set it reports 30 rows when the database really only has 1 row and I have verified this.
When I do a debug print to see the id's it is just the same record duplicated 30 times.
Below is the code that is ran.
Option Compare Database
Dim selectPlacement As QueryDef
Dim rs As Recordset
Private Sub Form_Current()
Set selectPlacement = CurrentDb.QueryDefs("SelectPlacement")
Me.AddPlacementForm.Form.Visible = False
selectPlacement.Parameters!stu = Me.student_id.Value
selectPlacement.Parameters!sem = Me.semester_id.Value
Me.AddPlacementForm.Form!lstStudent.Value = Me.student_id
Me.AddPlacementForm.Form!cmbSemester.Value = Me.semester_id
Me.PlacementsBlock1.Form.Filter = "[semester_id]= '" & Me.semester_id.Value & "'"
Me.PlacementsBlock2.Form.Filter = "[semester_id]= '" & Me.semester_id.Value & "'"
Me.PlacementsBlock1.Form.FilterOn = True
Me.PlacementsBlock2.Form.FilterOn = True
Set rs = selectPlacement.OpenRecordset
Call SetUpPlacements(rs)
rs.Close
Set selectPlacement = Nothing
End Sub
Private Sub SetUpPlacements(rs As Recordset)
If rs.RecordCount = 0 Then
Me.PlacementsBlock1.Form.Visible = False
Me.PlacementsBlock2.Form.Visible = False
Me.AddPlacementForm.Form.Visible = True
ElseIf rs.RecordCount = 1 Then
rs.MoveFirst
If rs!block = 1 Then
Me.PlacementsBlock1.Form.Visible = False
Else
Me.PlacementsBlock2.Form.Visible = False
End If
Me.AddPlacementForm.Form.Visible = True
Else
Me.PlacementsBlock1.Form.Visible = True
Me.PlacementsBlock2.Form.Visible = True
Me.AddPlacementForm.Form.Visible = False
End If
End Sub
And below is the query that is in the query def.
SELECT *
FROM student_placements
WHERE (((student_placements.student_id)=[stu]) AND ((student_placements.semester_id)=[sem]));
Any help with this would be much appreciated.
You are using the recordset without proper initialization, and thus your call to rs.RecordCount does not return the proper value.
You would need to check for an empty recordset via If rs.EOF and rs.BOF Then. To get the proper record count, you will need to call rs.MoveLast. Before, the record count is unreliable.
See http://allenbrowne.com/ser-29.html (traps 3 and 4) for more information.

Automatically Close Excel Compatibility Checker window

I have a VBA module that creates 2 Excel spreadsheets based on an MS Access temp table.
Each time a the second Excel spreadsheet is created, there is an Excel Compatibility Checker pop up window that appears. I am looking to automatically "click" 'Continue' on this pop up window each time the loop runs. How do I do this?
Refer to the section: 'Add step to click (Continue) button on pop-up window in the code below
Function ADMIN_Resource()
Dim rs As New ADODB.Recordset
Dim cn As New ADODB.Connection
Set cn = CurrentProject.Connection
Dim rowcount As Long
Dim tblcount As Integer
Dim i As Integer
DoCmd.SetWarnings False
'*****************************************************************************************************************************************************************
' Data pull from source ACCESS DB
'*****************************************************************************************************************************************************************
'On Error GoTo ErrorHandler
'Pull in all data from ACTUAL_ADMIN_TABLE into Main Temp Table
SQL = "SELECT Project_ID, Resource_ID, Allocation_Year, Jan, Feb, Mar, Apr, May, " & _
"Jun, Jul, Aug, Sep, Oct, Nov, Dec INTO tmp_ADMIN_TABLE FROM ACTUAL_ADMIN_TABLE ORDER BY Resource_ID ASC"
DoCmd.RunSQL SQL
'Add counter column to main temp table
SQL = "ALTER TABLE tmp_ADMIN_TABLE ADD COLUMN ID COUNTER(1,1)"
DoCmd.RunSQL SQL
'Set the number of files to create
SQL = "SELECT count(*) as rowcount from ACTUAL_ADMIN_TABLE"
rs.Open SQL, cn
rowcount = rs!rowcount
rs.Close
tblcount = rowcount / 500 + 1
For i = 1 To tblcount
'Create Sub Temp Table
SQL = "SELECT * into tmp_ADMIN_TABLE" & i & " FROM tmp_ADMIN_TABLE" & _
" WHERE ID <=500*" & i
DoCmd.RunSQL SQL
'Delete ID column on Sub Temp Table
SQL = "ALTER TABLE tmp_ADMIN_TABLE" & i _
& " DROP COLUMN ID;"
DoCmd.RunSQL SQL
'Delete the top 500 records from Main Temp Table
SQL = "DELETE * FROM tmp_ADMIN_TABLE" & _
" WHERE ID <=500*" & i
DoCmd.RunSQL SQL
Dim strTable As String
Dim strWorksheetPath As String
'*****************************************************************************************************************************************************************
'Create RAW Data files (might not need this step)
'*****************************************************************************************************************************************************************
'Location of RAW Data file
strWorksheetPath = "C:\test\ADMIN_RSRC\"
'RAW Data file name
strWorksheetPath = strWorksheetPath & "RAW_ADMIN-" & i & ".xls"
'RAW Data file tab name
strTable = "tmp_ADMIN_TABLE" & i
'Command to create RAW data file using parameters from above
DoCmd.TransferSpreadsheet transfertype:=acExport, spreadsheettype:=acSpreadsheetTypeExcel9, TableName:=strTable, FileName:=strWorksheetPath, hasfieldnames:=True
'First set of error handling
'ErrorHandlerExit:
' Exit Function
' 'Next i
'
'ErrorHandler:
' MsgBox "Error No: " & Err.Number _
' & "; Description: " & Err.Description
' Resume ErrorHandlerExit
'*****************************************************************************************************************************************************************
'Create Second Excel file based on RAW Data file
'*****************************************************************************************************************************************************************
'Select data from temp table
Dim rss As New ADODB.Recordset
SQL = "SELECT * from tmp_ADMIN_TABLE" & i
rss.Open SQL, cn
'CurrentProject.Connection.Execute SQL
'Open new instance of Execl
Dim x As New Excel.Application
'Dim x as New evba
Dim w As Workbook
Dim s As Worksheet
Dim r As Range
Dim d As String
Dim e As String
'Template file name and location
d = "C:\test\UploadTemplate"
'Open Template file based on locaiton with the old Excel extension
Set w = workbooks.Open(d & ".xls")
'Open Specific Template tab
Set s = w.Sheets("Resource Tab")
'Range of Excel cells to load data to
Set r = s.Range("A3:O502")
'Copy records from ACCESS temp table to Excel template document's specified locaiton
r.CopyFromRecordset rss
'Save Excel file
w.SaveAs d & i
'Add step to click (Continue) button on pop-up window
'*******************************************************************************
'RIGHT HERE
'(This is where I need help closing the Excel - Compatibility Checker window)
'Any suggestions
'*******************************************************************************
'Close current record set
rss.Close
Set rss = Nothing
'Delete current ACCESS temp table
SQL = "DROP TABLE tmp_ADMIN_TABLE" & i
DoCmd.RunSQL SQL
ThisWorkbook.Saved = True
w.Close
x.Quit
Set r = Nothing
Set s = Nothing
Set w = Nothing
Set x = Nothing
'Second set of error handling
'ErrorHandlerExit:
' Exit Function
' 'Next i
'ErrorHandler:
' MsgBox "Error No: " & Err.Number _
' & "; Description: " & Err.Description
' Resume ErrorHandlerExit
'
Next i
'Delete the main temp table from ACCESS
SQL = "DROP TABLE tmp_ADMIN_TABLE"
DoCmd.RunSQL SQL
End Function
Try this
'
'~~> Rest of your code
'
With W
.CheckCompatibility = False
.SaveAs d & i
.Close
.CheckCompatibility = True
End With
'
'~~> Rest of your code
'
On a separate note. You are not specifying the FileFormat while saving? The syntax is
W.SaveAs FilePath, Fileformat:=FF
Where
FilePath can be something like "C:\MyFile.xls" and FF like 56
Here is a basic list of File Formats
50 = xlExcel12 (Excel Binary Workbook in 2007-2013 with or without macro's, xlsb)
51 = xlOpenXMLWorkbook (without macro's in 2007-2013, xlsx)
52 = xlOpenXMLWorkbookMacroEnabled (with or without macro's in 2007-2013, xlsm)
56 = xlExcel8 (97-2003 format in Excel 2007-2013, xls)
Try
Application.DisplayAlerts = False
' your code to create Excel spreadsheet
Application.DisplayAlerts = True
Remember to set DisplayAlerts to true at some point in your code or Excel won't display any alerts.