Converting Macros to VBA from Outside Current Database - ms-access

I'd like a way to programatically convert Access macros to VBA modules. I know how to do this manually. I was working with some code to do this within the current database and I got it to work. However, I would like to be able to do this outside of the current database. I plan to have this program housed with other utility type programs in the same database. Below is my code. I am getting a message that says, "Microsoft Access cannot find the test1 you referenced in the Object Name arguement. Do you have any suggestions on how to acheive what I want to acheive?
Private Sub Command2_Click()
MsgBox "start here"
Dim strDB As String
Dim appAccess As Access.Application
Dim m As Object
strDB = "C:\Users\me\Desktop\testme.accdb"
Set appAccess = New Access.Application
appAccess.OpenCurrentDatabase strDB
For Each m In appAccess.CurrentProject.AllMacros
Debug.Print m.Name
DoCmd.SelectObject acMacro, m.Name, True
DoCmd.RunCommand acCmdConvertMacrosToVisualBasic
Next
Set appAccess = Nothing
End Sub

DoCmd is a member of the Application object. Ask those commands to work from the new Application object instance you created (appAccess) instead of the Application instance which is running your Command2_Click() procedure.
appAccess.DoCmd.SelectObject acMacro, m.Name, True
appAccess.DoCmd.RunCommand acCmdConvertMacrosToVisualBasic
In other words, basically do the same for DoCmd as you did with appAccess.OpenCurrentDatabase and appAccess.CurrentProject ... you associated them to the specific Application instance.

Related

Show Users on Access Database

I am trying to show all the users that is currently on my Access database. I am using a VBA code that I found online and am trying to modify it to my needs. I am trying to get all the available users and display it on List Box on my form called "ListUsers".
The code is able to output to the debug window but I'm unable to update my list box. I get the following error: "Run-time error '6014': The RowSourceType property must be set to 'Value List' to use this method." I looked on the property window for that list box and couldn't find anything related to RowSourceType. I have tried a few different suggestions online but I am still unable to update the list box, so I wanted to see if anyone here may have some ideas. My code is below, I placed the VBA code on a button click.
Option Compare Database
Option Explicit
Private Sub cmd_Users_Click()
Dim cn As New ADODB.Connection
Dim rs As New ADODB.recordset
Dim i, j As Long
Set cn = CurrentProject.Connection
' The user roster is exposed as a provider-specific schema rowset
' in the Jet 4.0 OLE DB provider. You have to use a GUID to
' reference the schema, as provider-specific schemas are not
' listed in ADO's type library for schema rowsets
Set rs = cn.OpenSchema(adSchemaProviderSpecific, _
, "{947bb102-5d43-11d1-bdbf-00c04fb92675}")
'Output the list of all users in the current database.
Debug.Print rs.Fields(0).Name, "", rs.Fields(1).Name, _
"", rs.Fields(2).Name, rs.Fields(3).Name
While Not rs.EOF
Debug.Print rs.Fields(0), rs.Fields(1), _
rs.Fields(2), rs.Fields(3)
ListUsers.AddItem "'" & rs.Fields(0) & "-" & rs.Fields(1) & "'"
rs.MoveNext
Wend
End Sub
I figured it out... I had to set the RowSourceType on the code. I added the following to the button click event:
Me.ListUsers.RowSourceType = "Value List"
There is also a good post here:
Ms Access AddItem with VBA

MS Access macro for exporting to Excel hits limit of 65k records

I have a macro (created with the macro wizard) which runs a number of queries and then outputs a table to excel. The table has more then the 65,000 records limit for exporting formatted tables. How can I export the table without formatting in the macro? Here is the error I receive after I run the macro.
I know you are using access vba to export the records but have you thought about using a datalink to your query from excel and using the access vba to open the excel file and refresh the data table? this will definitely eliminate any issues with max rows and should not have any failure issues due to export size. If you need more info on how to do that let me know and I'll add more info here.
Here is the code requested by Anthony Griggs above. But it is a VBA solution, not a macro solution, so not directly responsive to the question as posted. This was how I worked around the problem and have had this successfully in production for a long time.
Be sure to add the reference to "Microsoft ActiveX Data Objects 2.8 Library" (or current version for you) and also the "Microsoft Excel 12.0 Object Library" (or current version for you) before using this code. The save changes and quit at the end are critical, otherwise it leaves Excel open in the background that you have to kill via task manager.
Dim rs As New ADODB.Recordset
Dim xl As New Excel.Application
Dim xlWb As Excel.Workbook
Dim xlRange As Excel.Range
xl.Visible = False
xl.ScreenUpdating = False
vcurfilename = "MyFilename.XLSX”
Set xlWb = xl.Workbooks.Open(vcurfilename, 0, False, 5, "password", "password")
rs.Open "Select * from qryMyAccessQuery", CurrentProject.Connection, adOpenForwardOnly, adLockReadOnly
Set xlRange = xlWb.Worksheets("MyExcelSheetName").Range("A1").Offset(1, 0)
xlWb.Sheets("MyExcelSheetName ").Range("a2:bq25000").ClearContents
xlRange.Cells.CopyFromRecordset rs
xl.Range("Table1").Sort key1:=xl.Range("Table1[[#All],[MyColumnName]]"), _
order1:=xlAscending, Header:=xlYes
On Error Resume Next
xl.Range("table1").Columns("A").SpecialCells(xlCellTypeBlanks).EntireRow.Delete
On Error GoTo 0
rs.Close
xl.Range("table1").ListObject.HeaderRowRange.Find("MyColumnName1").EntireColumn.NumberFormat = "dd-MMM-yy"
xl.Range("table1").ListObject.HeaderRowRange.Find("MyColumnName2").EntireColumn.NumberFormat = "dd-MMM-yy"
xl.Range("table1").ListObject.HeaderRowRange.Find("MyColumnName3").EntireColumn.NumberFormat = "dd-MMM-yy"
xlWb.Close SaveChanges:=True
xl.Quit
DoEvents

AutoExec Module not Initiating

My data storage form has a new module (AutoExec) which is meant to test the connection to a SQL server db upon opening the form. Only it is not firing when opened. I was wondering if there was something in my code causing this, this is my first Module so I am not familiar with the proper forms yet.
Public Sub AutoExec()
Dim cnn As ADODB.Connection
Dim localrst As New ADODB.Recordset
Dim remoterst As New ADODB.Recordset
Set cnn = New ADODB.Connection
cnn.Open "Provider=SQLOLEDB; Data Source=DB\P003,49503; Initial Catalog=HRLearnDev;" _
& "User Id=USERNAME; Password=PASSWORD;"
If cnn.State = adStateOpen Then
MsgBox ("You have an established connection.")
Else
MsgBox ("Cannot connect to remote server. Data will be stored locally to CDData Table until application is opened again.")
End If
cnn.Close
Dim rst As New ADODB.Recordset
End Sub
When a database includes a macro named AutoExec, Access will run that macro at database startup.
In order for that to work, AutoExec must be an Access macro object. In your case, you have a VBA procedure named AutoExec. Since that is not a macro object, Access does not run the procedure automatically at database startup.
I suggest you create a VBA function ...
Public Function Startup()
Add the code from the body of your AutoExec procedure to the function.
Then create a new Access macro (an actual Access macro object --- on the ribbon in Access 2007, choose Create->Macro), use the macro RunCode action to run your new Startup() function. Name that macro object as AutoExec.
Here is a screenshot of my simple AutoExec example macro open in Design View.

Help Debugging this Code to Convert for .adp file type

I had a form with some VB code that was using Access 2003. Recently we wanted to use the same form as a small front end interface for another database that has a SQL Server backend. However, the file type for this project in Access is .adp and not all of the vb code is working properly. If you could help me fix the bugs in this code:
Private Sub SurveyNameCombo_AfterUpdate()
Dim db_CFC As DAO.Database
Set db_CFC = CurrentDb
Dim rst As DAO.Recordset, query As String, count As Integer
query = "SELECT DISTINCT SurveyID FROM tbl_SurveyMeta WHERE SurveyName = " & Chr(34) & Me.SurveyNameCombo.Value & Chr(34)
Set rst = db_CFC.OpenRecordset(query)
count = rst.RecordCount
If count > 1 Then
Me.SurveyIDCombo.RowSource = query
Else
rst.MoveFirst
Me.SurveyIDCombo.Value = rst.Fields(0).Value
Call SurveyIDCombo_AfterUpdate
End If
End Sub
It is throwing errors in the for the DAO.Database and DAO.Recordset.
Thank you for your help!
The error message "User-defined type not defined" on a line such as this ...
Dim db_CFC As DAO.Database
... means your application doesn't include a reference to the Microsoft DAO Object Library.
Open a code module, then check from the main menu in the VBE editor: Tools->References
Ordinarily the cure would be to place a check mark in the box next to Microsoft DAO Object Library, then click OK. However, your application is an ADP, and I don't know whether DAO can even be used in ADP. You can try. :-)
Sorry I can't tell you more. I quit using ADP a few years ago. Instead I use the MDB format with ODBC links to SQL Server database objects. Perhaps you could consider the same approach if you're unable to get the ADP version working as you need.

Converting DAO to ADO

I am working with an Access 2003 database that has a subroutine using DAO code. This code loops through the table definitions and refreshes the ODBC connection string. I would like to convert this to ADO so I do not have to reference the DAO object library. Here is the code ...
Public Sub RefreshODBCLinks(newConnectionString As String)
Dim db As DAO.Database
Dim tb As DAO.TableDef
Set db = CurrentDb
For Each tb In db.TableDefs
If Left(tb.Connect, 4) = "ODBC" Then
tb.Connect = newConnectionString
tb.RefreshLink
Debug.Print "Refreshed ODBC table " & tb.Name
End If
Next tb
Set db = Nothing
MsgBox "New connection string is " & newConnectionString, vbOKOnly, "ODBC Links refreshed"
End Sub
The part I am unsure of is how to loop through the tables and get/set their connection strings.
DAO is really best for that, you cannot refresh the link with ADO rather you would need to use ADOX (Some relevant code here).
You can acces the connection string via Jet OLEDB:Link Provider String
If avoiding a reference for DAO is your goal, you could just modify your existing procedure to use late binding for DAO. As an example, this sub should work without a reference set for DAO.
Public Sub DAO_without_reference()
Dim db As Object
Dim td As Object
Set db = CurrentDb
For Each td In db.TableDefs
Debug.Print td.Name
Next td
Set db = Nothing
End Sub
You would not have Intellisense to help you with DAO properties, methods, and constants while writing the code, but the code can still work with late binding.
I think this would be your easiest alternative if you are determined to avoid a DAO reference. However, I have never developed an Access project without a DAO reference, and I don't understand why you are opposed to adding it.
Edit: Also if you use late binding and any DAO constants, your code must use the constant value rather than the name.