Writing contents of table/query to excel using access vba - ms-access

I'm trying to write query/table contents from access to excel using vba. Currently my code is working to open new workbook every time and write the contents instead i need to specify the path of only one workbook to write. How do i specify the path in the code
My Access VBA
Function WriteToExcel()
Dim cnn As ADODB.Connection
Dim rst As New ADODB.Recordset
Dim strSQL As String
Dim strPath As String
Dim ws As Excel.Application
Dim i As Long
'*************************************************
'First stage is to take the first query and place it
'On sheet1
'*************************************************
Set cnn = CurrentProject.Connection
Set rst = New ADODB.Recordset
strSQL = "SELECT * FROM query1"
rst.Open strSQL, cnn, adOpenKeyset, adLockOptimistic, adCmdTableDirect
rst.MoveFirst
Set ws = CreateObject("Excel.Application")
With ws
.Workbooks.Add
.Visible = True
End With
ws.Sheets("sheet1").Select
For i = 0 To rst.Fields.Count - 1
ws.ActiveCell.Offset(0, i).Value = rst.Fields(i).Name
Next
ws.Range("a2").CopyFromRecordset rst
ws.Columns("A:Q").EntireColumn.AutoFit
rst.Close
End Function

I think there is a little confusion because of your variable prefixes. I've taken the liberty of amending your prefixes and answered the problem. You need Workbooks.Open(<<filename goes here>>) in place of Workbooks.Add. So try this code (untested as I do not have Access). Lastly there are other ways to populate Excel with data from Access, like a DataQuery. You might like to play with Excel GUI to investigate.
Function WriteToExcel()
Dim cnn As ADODB.Connection
Dim rst As New ADODB.Recordset
Dim strSQL As String
Dim strPath As String
Dim appXL As Excel.Application
Dim wb As Excel.Workbook
Dim wsSheet1 As Excel.Worksheet
Dim i As Long
'*************************************************
'First stage is to take the first query and place it
'On sheet1
'*************************************************
Set cnn = CurrentProject.Connection
Set rst = New ADODB.Recordset
strSQL = "SELECT * FROM query1"
rst.Open strSQL, cnn, adOpenKeyset, adLockOptimistic, adCmdTableDirect
rst.MoveFirst
Set appXL = CreateObject("Excel.Application")
With appXL
'Set wb = .Workbooks.Add '<--- to create a new workbook
Set wb = .Workbooks.Open("c:\temp\Myworkbook.xlsx") '<--- to open an exisiting workbook
.Visible = True
End With
Set wsSheet1 = wb.Sheets("sheet1")
wsSheet1.Select
For i = 0 To rst.Fields.Count - 1
wsSheet1.ActiveCell.Offset(0, i).Value = rst.Fields(i).Name
Next
wsSheet1.Range("a2").CopyFromRecordset rst
wsSheet1.Columns("A:Q").EntireColumn.AutoFit
rst.Close
End Function

Related

Download unique data into ms access table

I am using this code to download certain outlook mail fields into access. This works well however the code is keep on downloading duplicate mails. Is there a way to check for existing records and download records which are not in the table? Your answers would help a lot in my project
Private Sub getml()
Dim rst As DAO.Recordset
Dim OlApp As Outlook.Application
Dim inbox As Outlook.MAPIFolder
Dim inboxItems As Outlook.Items
Dim Mailobject As Object
Dim db As DAO.Database
Dim dealer As Integer
Set db = CurrentDb
Set OlApp = CreateObject("Outlook.Application")
Set inbox = OlApp.GetNamespace("Mapi").GetDefaultFolder(olFolderInbox)
Set rst= CurrentDb.OpenRecordset("mls")
Set inboxItems = inbox.Items
For Each Mailobject In inboxItems
With rst
.AddNew
!task= Mailobject.UserProperties.Find("taskID")
!tsktml= Mailobject.UserProperties.Find("timeline")
.Update
Mailobject.UnRead = False
End With
End If
Next
Set OlApp = Nothing
Set inbox = Nothing
Set inboxItems = Nothing
Set Mailobject = Nothi
End Sub
I am assuming that TaskID is a numeric unique identifier for tasks, not that familiar with Outlook objects. If so, you can use the following code to first check the task hasn't been imported already.
Private Sub getml()
Dim rst As DAO.Recordset
Dim OlApp As Outlook.Application
Dim inbox As Outlook.MAPIFolder
Dim inboxItems As Outlook.Items
Dim Mailobject As Object
Dim db As DAO.Database
Dim dealer As Integer
Set db = CurrentDb
Set OlApp = CreateObject("Outlook.Application")
Set inbox = OlApp.GetNamespace("Mapi").GetDefaultFolder(olFolderInbox)
Set rst= CurrentDb.OpenRecordset("mls")
Set inboxItems = inbox.Items
For Each Mailobject In inboxItems
With rst
.FindFirst "task =""" & Mailobject.UserProperties.Find("taskID") & """"
If .NoMatch
.AddNew
!task= Mailobject.UserProperties.Find("taskID")
!tsktml= Mailobject.UserProperties.Find("timeline")
.Update
Mailobject.UnRead = False
End If
End With
End If
Next
Set OlApp = Nothing
Set inbox = Nothing
Set inboxItems = Nothing
Set Mailobject = Nothing
End Sub

Access 2016 - Method or data member not found

This is my code:
Private Sub Command36_Click()
Dim dbs As DAO.Database
Dim rs As DAO.Recordset
Dim qdef As DAO.QueryDefs
Set dbs = CurrentDb
Set qdef = dbs.QueryDefs("qryGetDecisionFieldOfSelectedRecord")
Set rs = qdef.OpenRecordset
If rs.RecordCount > 0 Then
DoCmd.OpenReport "rptApplicationDeclinedLetter", acViewPreview, "qryApplicationLetter"
End If
End Sub
The compile error is triggered at Set rs = qdef.OpenRecordSet. Apologies if this is too obvious.
Correct this to:
Dim qdef As DAO.QueryDef

Next without For compile error

I am new to VBA and am working on a project which will display all current users who have a particular file open (MS Access). I am trying to populate a listbox with the computer name info but am getting an error when I try to run the button command.rs.Fields(0) is the only field I need as it is the computer name. I just need a list of all computer names connected.
Sub ShowUserRosterMultipleUsers()
Dim cn As New ADODB.Connection
Dim rs As New ADODB.Recordset
Set cn = CurrentProject.Connection
Set rs = cn.OpenSchema(adSchemaProviderSpecific, _
, "{947bb102-5d43-11d1-bdbf-00c04fb92675}"
'While Not rs.EOF
'Debug.Print rs.Fields(0), rs.Fields(1), _
'rs.Fields(2), rs.Fields(3)
'rs.MoveNext
'Wend
Do While Not rs.EOF
With List73
.AddItem rs.Fields(0)
End With
Next
End Sub
Sub ShowUserRosterMultipleUsers()
Dim cn As New ADODB.Connection
Dim rs As New ADODB.Recordset
Set cn = CurrentProject.Connection
Set rs = cn.OpenSchema(adSchemaProviderSpecific, _
, "{947bb102-5d43-11d1-bdbf-00c04fb92675}"
'While Not rs.EOF
'Debug.Print rs.Fields(0), rs.Fields(1), _
'rs.Fields(2), rs.Fields(3)
'rs.MoveNext
'Wend
Do While Not rs.EOF
With List73
.AddItem rs.Fields(0)
End With
Loop
End Sub

How can you convert an ACCDB to an MDB programmatically?

Is there a way to programmatically convert an Access 2010 ACCDB file to an Access 95/97 MDB file?
Here are some notes. I do not have an old version to play around with, so I do not know if you can import more than you can export:
Dim ws As Workspace
Dim db As Object
Dim tdf As TableDef
Dim qdf As QueryDef
Dim dbExp As Database
Dim acApp As New Access.Application
acApp.OpenCurrentDatabase "z:\docs\demo.accdb"
Set dbExp = acApp.CurrentDb
Set ws = DBEngine.Workspaces(0)
FName = "z:\docs\oldver95.mdb"
''Access 95
Set db = ws.CreateDatabase(FName, dbLangGeneral, dbVersion30)
''You can only export tables and a limited range of datatypes
For Each tdf In dbExp.TableDefs
If Left(tdf.Name, 4) <> "Msys" Then
acApp.DoCmd.TransferDatabase acExport, "Microsoft Access", _
FName, acTable, tdf.Name, tdf.Name
End If
Next
See http://msdn.microsoft.com/en-us/library/office/bb243161(v=office.12).aspx
A few notes using VBScript to demonstrate using the engine:
Dim objEngine
Dim objWS
Dim objDB
Dim db: db = "z:\docs\oldver95.mdb"
Set objEngine = CreateObject("DAO.DBEngine.36")
Set objDB = objEngine.OpenDatabase(db)
strSQL="SELECT * FROM Table1"
objDB.CreateQueryDef "Query1", strSQL

Display the result of a stored procedure in a Recordset on a form

The following code run a stored procedure based on a combobox that is selected in a form. I need to display the results in a form in Access. Here is the code:
Dim Cmd1 As ADODB.Command
Dim lngRecordsAffected As Long
Dim rs1 As ADODB.Recordset
Dim intRecordCount As Integer
'-----
Dim cnnTemp As ADODB.Connection
Set cnnTemp = New ADODB.Connection
cnnTemp.ConnectionString = "DRIVER=SQL Server;SERVER=****;" & _
"Trusted_Connection=No;UID=****;PWD=****;" & _
"Initial Catalog=IKB_QA;"
'Open Connection
cnnTemp.Open
Set Cmd1 = New ADODB.Command
Cmd1.ActiveConnection = cnnTemp
'---
With Cmd1
Dim localv As Integer
localv = [Forms]![start]![Selection]![cat_code]
.CommandText = "dbo.ix_spc_planogram_match"
.CommandType = adCmdStoredProc
.Parameters.Refresh
.Parameters("#catcode").Value = localv
Set rs1.Open = Cmd1.Execute(localv)
End With
End Sub
It's unclear to me which part of this problem you're having trouble with but maybe it's the binding part.
You can bind a form to an ADO recordset using the following code:
Set Me.Recordset = rs1
Just make sure your form has controls on it bound to the fields which will be in your recordset.