Vba code for 1 field from access form to excel - ms-access

What is the simplest VBA code I could put in an access form button that will export a field value to a specified cell in excel?

Please do search before submitting a question in StackOverflow. There a multiple answers to this question and you did not include sufficient background too.
Is your Excel open?
Is your Excel even created?
I
I'll attach the code to create a new instance of Excel, and write text to a specific cell.
Private Sub Button_Click()
Dim objExcel As Excel.Application
Dim objSheet As Excel.Workbook
Set objExcel = New Excel.Application
Set objSheet = objExcel.Workbooks.Open("C:\MyExcelfile.xlsx")
objExcel.Range("C6").Value = "Some text to write here"
objExcel.Range("D7").Value = me.textboxSomething.value
objSheet.save
Set objSheet = Nothing
objExcel.Quit
Set objExcel = Nothing
End sub
You have to deal with error handling in case of error.
Do note you have to add "Microsoft Excel 1#.0 Object library" reference, in your access vba editor, under tools menu.

Related

Opening a Mail Merge Word Document from an Access Database

I currently have a Microsoft Access Database (file format is 2007-2016) that we use to track open orders and print all the required documents. I have created a word document that pulls information from this database using MailMerge. This document works flawlessly by itself. Meaning that if I actually double click the document it opens correctly asking me if I want to pull the information from the database. The issue is that if I open it via a command button in the database I the document opens but I will not get the MailMerge dialog asking if I want to pull the information.
Here is the code I am using at the moment to open the document.
Private Sub Print_Click()
If IsNull(Me.DateShipped.Value) Then
Me.DateShipped = Date
End If
DoCmd.RunCommand acCmdSaveRecord
Dim wrdApp As Word.Application
Dim wrdDoc As Word.Document
Set wrdApp = CreateObject("Word.Application")
wrdApp.Visible = True
Set wrdDoc = wrdApp.Documents.Open("F:\Database\merge\INDIVIDUAL.docx")
Set wrdApp = Nothing
Set wrdDoc = Nothing
DoCmd.RunCommand acCmdSaveRecord
Any help will be appreciated.
Thank you
Joel

Microsoft Access 2016: Quitting Excel.Application

I'm attempting to export data from my Access database to an Excel workbook. Everything works fine, except that I can't get Excel to properly shut down after the export is complete. When I open up the Task Manager after the code executed, an instance of Microsoft Excel is always listed under Background Processes. I read various comments suggesting that the issue might be that, somewhere between creating the initial Excel.Application object and attempting to close it, another Excel.Application is secretly being created. As a result, I trimmed the code down to the point where all it does is creating and closing an Excel.Application object. Still the same result.
This is my code:
Sub testexcel()
Dim xl As Excel.Application
Set xl = Excel.Application
xl.Quit
Set xl = Nothing
End Sub
I'd appreciate any suggestions on what I have to change to get Excel to close properly. Thanks!
This code worked for me in the end:
Sub testexcel()
Dim xl as Excel.Application
Set xl = New Excel.Application
'Code
xl.Quit
Set xl = Nothing
End Sub
Apparently the 'New' keyword made all the difference.
You state that you're 'attempting to export data from my Access database ' - but you don't state how - - and there is more than 1 way to do this.
In Access the ribbon's External tab has the export feature. If one opens the data set (table or query) on screen and then manually does an export using this feature - the Excel application should not get opened at all. Have you sanity checked via this approach?
Use CreateObject("Excel.Application") instead.
Sub testexcel()
Dim xl As Excel.Application
Set xl = CreateObject("Excel.Application")
Stop ' so you can see in Task Manager / Process Explorer that EXCEL.EXE is there
xl.Quit
Set xl = Nothing
' and it's gone
End Sub

Display alerts are not enabling in excel file from access vba

I'm writing contents of tables from access to excel(Opening the excel file from access) After writing it i'm trying to save all workbooks in the appXL application. For that i'm making DispalyAlerts false before saving and trun on back after saving. After writing contents to excel i'm closing the access. After writing ,when i'm trying to close the excel, it is not giving any alerts like Do you want to save the contents?
My vba code
Sub Writexl()
Dim appXL As Excel.Application
Dim wb As Excel.Workbook
StrwbPath="C:\temp\sample.xls"
Set appXL = CreateObject("Excel.Application")
With appXL
Set wb = .Workbooks.Open(StrwbPath)
.Visible = True
End With
'here code for writing contents
'save workbook after writing
appXL.Application.DisplayAlerts = False
For Each w In appXL.Application.Workbooks
w.Save
Next w
appXL.Application.DisplayAlerts = True
DoCmd.Quit acQuitSaveAll
Application.Quit
End sub
You are setting the DisplayAlerts to the Application's Applicaiton
appXL.Application.DisplayAlerts = True
is conceptually equivalent to
Excel.Application.Application.DisplayAlerts = True
So the property is being set on the parent application to Excel.
Try
appXL.DisplayAlerts = True
After writing ,when i'm trying to close the excel, it is not giving
any alerts like Do you want to save the contents?
As #David Zemens says, why would it display a message to save all changes when you've already saved everything. Have you tried changing a cell and then exiting Excel?

An Access Form:How to get PDF of a access form

I have a Icon of PDF in my form that I have created in Access 2010. There are 3 tabs in that form; each tab have a separate form page and PDF icon is common for all the tabs.
Now I want that whenever a user click on that icon a PDF file of that form get created.
I have written this code
Private Sub cmdPrintReportPDF_Click()
Dim strDefaultPrinter As String
strDefaultPrinter = Application.Printer.DeviceName
**Set Application.Printer = Application.Printers("PDFCreator")**
'DoCmd.PrintOut acPrintAll
DoCmd.OpenReport "Graph_report", acViewNormal
Set Application.Printer = Application.Printers(strDefaultPrinter)
End Sub
But I'm getting the following error:
Invalid procedure call or argument on line no 4.
Set Application.Printer = Application.Printers("PDFCreator")
I have PDFCreator installed and this line, which triggers an error for you, does not trigger an error for me.
Set Application.Printer = Application.Printers("PDFCreator")
Go to the Immediate Window of the VB Editor and see if you also get an error with this line:
? Application.Printers("PDFCreator").DeviceName
If that also triggers an error, you probably don't have a printer whose DeviceName is PDFCreator. You can list the names of the printers with this procedure.
Public Sub ListPrinters()
Dim objPrinter As Printer
For Each objPrinter In Application.Printers
Debug.Print objPrinter.DeviceName
Next objPrinter
End Sub
However, with Access 2010, I think you can create a PDF without using your PDFCreator print device. At least this works for me with Access 2007, so I'm guessing it will work for you.
Private Sub cmdSaveAsPdf3_Click()
Dim strPath AS String
strPath = CurrentProject.Path & Chr(92) & "Sample3.pdf"
DoCmd.OutputTo acOutputForm, "fsubSample3", acFormatPDF, strPath
End Sub
That button click code creates a PDF (Sample3.pdf) of the form (fsubSample3) embedded in a page of my main form's tab control ... which is what I thought you wanted based on the original version of your question. Now it seems you're wanting to create a PDF of a report rather than a form. You can adapt the DoCmd.OutputTo line to use a report instead of a form.
Change this:
Set Application.Printer = Application.Printers("PDFCreator")
...to this:
Application.Printer = Application.Printers("PDFCreator")
Application.Printer is a property, not an object, so it doesn't use SET to change it.

Exporting data from MS Access to Excel using VBA

I have a table in MS Access, which has the following data to be exported to excel
Release numbers
Test cases
Results
After exporting to Excel I want to have distinct release numbers as rows starting from A2 and distinct test case name as columns starting from B1. There might be couple thousands records. Then each cell will be set to result tag. Additionally will need some fancy coloring/bordering stuff.
The question - is it possible to do this using VBA in Access and if yes what is the way to go? Any hint, sample, example, resource would be appreciated... I've googled but the most thing I came accross is DoCmd.TransferSpreadsheet or DoCmd.OutputTo which I believe will not do what I want. Saw some examples with CreateObject("Excel.Application") but not sure what are limitations and performance using this way.
I don't know if it would work for your case, but you might try adding the VBA code to an Excel document rather than the Access database. Then you could refresh the data from the Excel file and add the formatting there much easier. Here is one example:
http://www.exceltip.com/st/Import_data_from_Access_to_Excel_%28ADO%29_using_VBA_in_Microsoft_Excel/427.html
(Or see other examples at http://www.exceltip.com/exceltips.php?view=category&ID=213)
Again, it may not work for your case, but it may be an option to consider. Essentially, instead of pushing from Access, you would pull from Excel.
Yes, there are many cases when the DoCmd.TransferSpreadsheet command is inadaquate.
The easiest way is to reference the Excel xx.x Object model within Access (Early Binding). Create and test your vba export function that way. Then once you are satisfied with your output, remove the Excel object model reference, then change your objects to use use Late Binding using CreateObject. This allows you to easily have other machines that are using different versions of Excel/Access to use it just the same.
Here is a quick example:
Sub ExportRecordsetToExcel(outputPath As String, rs As ADODB.Recordset)
'exports the past due report in correct formattig to the specified path
On Error GoTo handler:
Const xlUP As Long = -4162 'excel constants if used need to be referenced manually!
Dim oExcel As Object
Dim oBook As Object
Dim oSheet As Object
Dim row As Long
If rs.BOF And rs.EOF Then
Exit Sub 'no data to write
Else
rs.MoveFirst
End If
row = 1
Set oExcel = CreateObject("Excel.Application")
oExcel.Visible = False 'toggle for debugging
Set oBook = oExcel.Workbooks.Add 'default workbook has 3 sheets
'Add data to cells of the first worksheet in the new workbook.
Set oSheet = oBook.worksheets(1)
Do While rs.EOF = False
oSheet.range("A" & row).value = rs.Fields("MyField").value
'increase row
row = row + 1
Loop
oBook.SaveAs (outputPath)
'tidy up, dont leave open excel process
Set oSheet = Nothing
Set oBook = Nothing
oExcel.Quit
Set oExcel = Nothing
Exit Sub
handler:
'clean up all objects to not leave hanging processes
End Sub