Access query to a macro enabled excel template using vba - excel

Im trying to put data from a query which requires a parameter into a excel template with marcos in it however I keep getting errors. Im getting the parameter from the form.
heres my code:
Private Sub exportButton_Click()
Dim XL As Excel.Application
Dim wbTarget As Workbook
Dim qdfResults As QueryDef
Dim rsResults As Recordset
'Set up refernce to the query to export
Set qdfResults = CurrentDb.QueryDefs("MarksQuery")
qdfResults.Parameters("Forms!comp!competition") = Forms!comp!competition
'Execute Query
Set rsResults = qdfResults.OpenRecordset()
'reference excel
Set XL = CreateObject("Excel.Application")
'refernce workbook
Set wbTarget = XL.Workbooks.Open("C:\Users\user\Documen…\folder\resultTemplate.xltm")
'clear excel sheet
wbTarget.Worksheets("marktable").Cells.ClearContents
'paste data from query to worksheet
wbTarget.Worksheets("markTable").Cells(1, 1).CopyFromRecordSet rsResults
'save workbook
** 1) 'wbTarget.SaveAs ("C:\Users\user\Documents
\folder\resultTemplate1.xlsm")
** 2) wbTarget.SaveAs FileName:="C:\Users\user\Documents\folder\resultTemplate1.xlsm",
FileFormat:=xlOpenXMLWorkbookMacroEnabled
'clear variables
Set wbTarget = Nothing
Set XL = Nothing
Set qdfResults = Nothing
End Sub
with 1) i could get the data into a work book but without the macros
with 2) i can get the data in and macro but wont save properly
any suggestions?
EDIT**
by wont save properly i mean that it is creating a temperory file that i cannot save
and now it wont even created that, now its creating a file with 0 bytes and no type
cant answer by own question yet but until I can heres my working code:
The only problem I can see was that wbTarget.Close and XL.Quit werent used which caused the module to still run and the file therefore wasn't completely saved but temporary. Credit to #Gord Thompson
Private Sub exportButton_Click()
Dim XL As Excel.Application, wbTarget As Workbook
Dim qdfResults As QueryDef
Dim rsResults As Recordset
Set XL = New Excel.Application
Set wbTarget = XL.Workbooks.Open("C:\Users\user\Documents\folder\ResultsTemplate.xltm")
Set qdfResults = CurrentDb.QueryDefs("MarksQuery")
qdfResults.Parameters("Forms!comp!competition") = Forms!comp!competition
Set rsResults = qdfResults.OpenRecordset()
wbTarget.Worksheets("markTable").Cells(1, 1).CopyFromRecordSet rsResults
wbTarget.SaveAs "C:\Users\user\Documents\folder\Results.xlsm", xlOpenXMLWorkbookMacroEnabled
wbTarget.Close
Set wbTarget = Nothing
XL.Quit
End Sub

Strange behaviour in Office automation projects can often be the result of failing to properly Close objects and Quit applications. In this case adding
wbTarget.Close
and
XL.Quit
statements appears to have resolved the issue.

The only problem I can see was that wbTarget.Close and XL.Quit werent used which caused the module to still run and the file therefore wasn't completely saved but temporary. Credit to #Gord Thompson
Private Sub exportButton_Click()
Dim XL As Excel.Application, wbTarget As Workbook
Dim qdfResults As QueryDef
Dim rsResults As Recordset
Set XL = New Excel.Application
Set wbTarget = XL.Workbooks.Open("C:\Users\user\Documents\folder\ResultsTemplate.xltm")
Set qdfResults = CurrentDb.QueryDefs("MarksQuery")
qdfResults.Parameters("Forms!comp!competition") = Forms!comp!competition
Set rsResults = qdfResults.OpenRecordset()
wbTarget.Worksheets("markTable").Cells(1, 1).CopyFromRecordSet rsResults
wbTarget.SaveAs "C:\Users\user\Documents\folder\Results.xlsm", xlOpenXMLWorkbookMacroEnabled
wbTarget.Close
Set wbTarget = Nothing
XL.Quit
End Sub

Related

Excel Vba Copy Method of Worksheet fails - Copy from xlApp to ThisWorkbook

I posted a question recently on interacting with another WB in a separate instance of Excel.
How to add Open Workbook to "Application.Workbooks" collection and/or interact with Workbook
But I had hardcoded the copy/paste range for testing, and now I'm having trouble with coping the entire worksheet to the "main wb". Eg: xlApp.Worksheets(1).Copy After:=Application.ActiveWorkbook.Sheets(1)
I get the error Copy Method of Worksheet Failed and ideas how to adjust this to work?
Public Sub Copy_External_WB()
Dim xlApp As Excel.Application, xlBook As Worksheet, i As Long
For i = 1 To 10
On Error Resume Next
Set xlApp = GetObject("Book" & i).Application
If Err.Number = -2147221020 Then
Err.Clear: On Error GoTo 0
Else
On Error GoTo 0
Exit For
End If
Next i
If Not xlApp Is Nothing Then
Set xlBook = xlApp.Worksheets(1)
Debug.Print xlApp.hWnd, Application.hWnd
Else
MsgBox "No Excel session with Book(1 - 10) open could be found..."
xlApp.Quit: Exit Sub
End If
'Dim CopyFrom As Range
'Set CopyFrom = xlBook.Range("A1:AQ56")
'Dim DS As Worksheet
'Set DS = ThisWorkbook.Worksheets("Merged")
'DS.Range("A1:AQ56").Resize(CopyFrom.Rows.Count).Value = CopyFrom.Value
xlApp.Worksheets(1).Copy After:=Application.ActiveWorkbook.Sheets(1)
xlApp.DisplayAlerts = False
xlApp.Quit
xlApp.DisplayAlerts = True
Set xlApp = Nothing
End Sub
You cannot copy a whole sheet object between different Excel instances.
Options:
Use VBA to save the other workbook to file, then open it in the instance where your code is running, and copy the sheet to your workbook
Copy (eg) the UsedRange from the other instance's worksheet, then paste in your primary instance workbook

Access to the data of a workbook in another repertory

I want to get the access of the data in a workbook in another repertory but I don't know the syntax, can you help me please ?
I have tried something like that but it doesn't work
Workbooks("U:\a.xlsx").Sheets("a").Range("A2")
To read a value you need to open that file first.
Dim MyWb As Workbook
Set MyWb = Workbooks.Open(Filename:="U:\a.xlsx", ReadOnly:=True) 'readonly if you only need to read
'read the value
Debug.Print MyWb.Worksheets("a").Range("A2")
'close it after reading
MyWb.Close SaveChanges:=False
Or if you want to do it hidden in the background without showing the workbook:
'open a new hidden Excel
Dim ExApp As Excel.Application
Set ExApp = New Excel.Application
ExApp.Visible = False
'open the workbook in that hidden ExApp
Dim MyWb As Workbook
Set MyWb = ExApp.Workbooks.Open(Filename:="U:\a.xlsx", ReadOnly:=True)
'read the value
Debug.Print MyWb.Worksheets("a").Range("A2")
'close it after reading
MyWb.Close SaveChanges:=False
'close hidden Excel
ExApp.Quit
Here a proper error handling might be useful to ensure the ExApp is closed in case of any error. Otherwise the process will stay open.
You'll need to open the workbook to access it.
Like:
Dim otherwb as Workbook
Set otherwb = Workbooks.Open("U:\a.xlsx")
Dim otherwbRange as Range
Set otherwbRange = otherwb.Sheets("a").Range("A2")
You need to create an Object for the workbook first.
Try something like:
Dim excel_wb2 As Excel.Workbook
Set excel_wb2 = Excel.Workbooks.Open("U:\a.xlsx")
x = excel_wb2.Sheets("a").Range("A2")

how to print excel file via vb6?

I have an excel file that was created by vb6 application and after I save it, I want it to be printed into the default printer..,
Tnx, any help would be appreciated.
Private Sub Command1_Click()
Dim xlApp As Excel.Application
Dim xlWB As Excel.Workbook
Dim xlSH As Excel.Worksheet
'open excel application
Set xlApp = New Excel.Application
'Open excel workbook
Set xlWB = xlApp.Workbooks.Open(FileName:="C:\YourFile.xls")
'There are two ways to access specific worksheets
'By index number (the first worksheet in this case)
Set xlSH = xlWB.Worksheets(1)
'or by the Sheet's Name
Set xlSH = xlWB.Worksheets("TestSheet")
PrintSheet xlSH, "MyFoot", "MyHead"
'Close workbook (optional)
xlWB.Close
'Quit excel (automatically closes all workbooks)
xlApp.Quit
'Clean up memory (you must do this)
Set xlWB = Nothing
Set xlApp = Nothing
End Sub
Sub PrintSheet(sh As Worksheet, strFooter As String, strHeader As String)
sh.PageSetup.CenterFooter = strFooter
sh.PageSetup.CenterHeader = strHeader
sh.PrintOut
End Sub
Yet, to answer your question, you can use :
ActiveWorkbook.PrintOut Copies:=1, Collate:=True
and you can find much information here : http://www.exceltip.com/excel_tips/Printing_in_VBA/210.html
Anyway, i insist, you should accept answers from your previous questions or people won't care answering your new ones.
Max

Editing Excel spreadsheats from Word with VBA

How do I edit excel spreadsheets from word using VBA?
First you need to set a reference to the version of Excel you are running. In the VBE go to Tools>References and click Microsoft Excel 12.0 Object Library (12.0 for 2007, 11.0 for 2003) etc.
Then you can code something like this (opens a new instance of Excel, opens, edits and saves a new workbook). You'd use GetObject to access a running instance of Excel:
Sub EditExcelFromWord()
Dim appExcel As Excel.Application
Dim wb As Excel.Workbook
Dim ws As Excel.Worksheet
Set appExcel = CreateObject("Excel.Application")
With appExcel
.Visible = True
Set wb = .Workbooks.Add
Set ws = wb.Worksheets(1)
ws.Range("A1").Value2 = "Test"
wb.SaveAs ThisDocument.Path & Application.PathSeparator & "temp.xls"
Stop 'admire your work and then click F5 to continue
Set ws = Nothing
Set wb = Nothing
Set appExcel = Nothing
End With
End Sub

Excel 2007 ODBC data populates when opened via Windows Explorer, but not when opened via Access VBA

I have an Excel 2007 workbook that contains an ODBC data connection (to FoxPro, if that matters). The connection is set to "refresh data when opening the file."
When I go into File Explorer and open the workbook, the data populates into the spreadsheet as it should. However, when I execute a function in Access VBA that opens the workbook, the data from the ODBC connection does not populate.
Why would it make a difference which way the workbook is opened? And more importantly, how can I get the data to populate when the workbook is opened via Access VBA?
Here is the Access VBA code that opens the workbook:
Public Sub Subform_cmdOpenFile_Click(frm As Form)
Dim rs As Recordset
Dim ftiSuperclass As FilingTemplateInterface
Set rs = frm.RecordsetClone
If (rs.BOF Or rs.EOF) Then GoTo PROC_EXIT
Set ftiSuperclass = New FilingTemplateInterface
ftiSuperclass.ShowWorkbook rs!Directory & frm!Filename
PROC_EXIT:
On Error Resume Next
rs.Close
Set rs = Nothing
ftiSuperclass.QuitExcel
Set ftiSuperclass = Nothing
Exit Sub
PROC_ERROR:
Resume PROC_EXIT
End Sub
Friend Sub ShowWorkbook(strFilename As String)
Dim fso As New Scripting.FileSystemObject
Dim appExcel As New Excel.Application
appExcel.Workbooks.Open Filename:=strFilename, AddToMRU:=True
appExcel.visible = True
Set appExcel = Nothing
End Sub
Resolved by adding the line of code noted below, to force connection refresh on open:
Friend Sub ShowWorkbook(strFilename As String)
Dim fso As New Scripting.FileSystemObject
Dim appExcel As New Excel.Application
appExcel.Workbooks.Open Filename:=strFilename, AddToMRU:=True
appExcel.ActiveWorkbook.Connections("ConnectionName").Refresh 'added this line
appExcel.visible = True
Set appExcel = Nothing
End Sub

Resources