I just encountered two issues. For one thing, I can't seem to run a Make Table Query in Access, from Excel. I'm getting an error message that says 'Table Risk Rating already exists'. There must be a way to run a Make table Query from Excel. Also, and more importantly, my code seems very unstable. If I run it by hitting F8 over and over, everything works fine. If I run it by a button click event, I get the following error: 'The remote server machine does not exist or is unavailable'. It seems like Excel is losing it's communication with Access. That's just a guess. This thing is on my desktop, so I don't really think this the remote machine is unavailable.
Here is my code.
Sub RunQueriesInAccess()
Dim AC As Access.Application
Set AC = CreateObject("Access.Application")
strDatabasePath = ThisWorkbook.Path & "\Database1.accdb"
With AC
.OpenCurrentDatabase (strDatabasePath)
.CurrentDb.Execute "qry_RISK_RATING"
.CurrentDb.Execute "qry_Delete_ALLL"
Set DB = AC.CurrentDb
Set qry = DB.QueryDefs("qry_DATA_HIST")
qry.Parameters(0) = Worksheets("Impact Analysis New").Range("B1").Value
qry.Execute
Set qry = DB.QueryDefs("qry_LIMIT_HIST")
qry.Parameters(0) = Worksheets("Impact Analysis New").Range("B1").Value
qry.Execute
.Quit
End With
ActiveWorkbook.RefreshAll
End Sub
Any idea what's going on here?
Thanks!!
I'm going to answer what I know, but can't replicate vague instability.
Using .CurrentDb.Execute, you can execute action queries, but can't overwrite tables using a CREATE TABLE or SELECT ... INTO query.
Using .DoCmd.SetWarnings False and .DoCmd.OpenQuery, however, you can.
You can use .DoCmd.SetParameter if your parameterized queries are also creating tables.
You are using a lot of undeclared variables in your piece of code. I'm going to declare them for you and use late binding for the Access.Application, instead of your early/late binding combo thing you got there.
Sub RunQueriesInAccess()
Dim AC As Object
Set AC = CreateObject("Access.Application")
Dim strDatabasePath As String
strDatabasePath = ThisWorkbook.Path & "\Database1.accdb"
With AC
.OpenCurrentDatabase (strDatabasePath)
Dim db As Object
Set db = .CurrentDb
.DoCmd.SetWarnings False
.DoCmd.OpenQuery "qry_RISK_RATING"
.DoCmd.OpenQuery "qry_Delete_ALLL"
Dim qry As Object
Set qry = db.QueryDefs("qry_DATA_HIST")
qry.Parameters(0) = Worksheets("Impact Analysis New").Range("B1").Value
qry.Execute
Set qry = db.QueryDefs("qry_LIMIT_HIST")
qry.Parameters(0) = Worksheets("Impact Analysis New").Range("B1").Value
qry.Execute
.DoCmd.SetWarnings True
.Quit
End With
ActiveWorkbook.RefreshAll
End Sub
Related
I have a VBA procedure in Word that checks to see if a QueryDef exists in an Access database. It was working fine until a few days ago, when it started crashing Word.
The issue seems to be this line: For Each qdf In db.QueryDefs. This is the line on which Word hangs and then crashes. I don't think it's my code because I have created a very basic test procedure in a new Word document that is just a loop with nothing in it (see below) and created a new Access database and it still crashes.
A connection to the database is successfully made as I get the locked database file. And this code will successfully execute and print to immediate window: Debug.Print db.QueryDefs.Count
I also tested this basic procedure with the empty loop in Excel and it crashes there too. I also updated Office (I'm on Office 365, desktop version of Office). Is there something I'm missing?
Reference to: Microsoft Office 16.0 Access Database Engine Object Library
Option Explicit
Sub Test()
Dim qdf As DAO.QueryDef
Dim db As DAO.Database
Set db = OpenDatabase("DatabasePathAndFileName")
Debug.Print db.QueryDefs.Count
For Each qdf In db.QueryDefs
Next qdf
End Sub
Hit F9 as you step through the code and post back with the exact error. Also, have you restarted the machine recently? I have seen CTRL-Breaks build up over time, and cause all kinds of weirdness, but a restart usually fixes everything. Finally, what changed since it was working last??!!
Try this. What happens?
Public Sub ExecParameterQuery()
Dim dbs As DAO.Database
Dim qdf As DAO.QueryDef
Set dbs = CurrentDb
Set qdf = dbs.QueryDefs("myActionQuery")
'Set the value of the QueryDef's parameter
qdf.Parameters("Organization").Value = "Microsoft"
'Execute the query
qdf.Execute dbFailOnError
'Clean up
qdf.Close
Set qdf = Nothing
Set dbs = Nothing
End Sub
Try stepping through the collection to see if it is a specific query that causes the problem:
Sub Test()
Dim qdf As DAO.QueryDef
Dim db As DAO.Database
Set db = OpenDatabase("DatabasePathAndFileName")
If db.QueryDefs.Count > 0 Then
For Each qdf In db.QueryDefs
MsgBox qdf.Name
Next qdf
End If
End Sub
So I have this code in vba which exports data from excel to access. This works fine running the first time and then running the second time "Runtime error 462: The remote server does not exist or is unavailable" shows up.
However if i was to restart excel, then it seems to works fine again the first time. I've tried googling solutions however most of them say set any objects to Nothing and empty variables and it still doesn't work.
Sub AccImport()
Dim acc As New Access.Application
Dim myValue As Variant
myValue = InputBox("Enter table name for access export")
acc.OpenCurrentDatabase "C:\Users\User 1\Documents\Database21.accdb"
acc.DoCmd.TransferSpreadsheet _
TransferType:=acImport, _
SpreadSheetType:=acSpreadsheetTypeExcel12Xml, _
TableName:=myValue, _
Filename:=Application.ActiveWorkbook.FullName, _
HasFieldNames:=True, _
Range:="Sheet2$A1:AL104"
CurrentDb.TableDefs(myValue).Fields("F4").Properties!ColumnWidth = 2500
CurrentDb.TableDefs(myValue).Fields("F7").Properties!ColumnWidth = 2500
acc.CloseCurrentDatabase
acc.Quit
Set acc = Nothing
myValue = Empty
MsgBox " The data has been exported"
Application.DisplayAlerts = False
Sheets("Sheet2").Select
ActiveWindow.SelectedSheets.Delete
Range("A1").Select
Application.DisplayAlerts = True
End Sub
The below snippet of code is where this error seems to show up when running the second time round. Any help would be much appreciated. Thanks
CurrentDb.TableDefs(myValue).Fields("F4").Properties!ColumnWidth = 2500
I've gone for a code tidy-up approach which should sort the problem.
Examinig each of the objects, from the code break line, in the Immediate Window would also help (e.g. what does "?Currentdb.Name" return)
1) VBA supports New as part of an object declaration, but... (best you research this bit. From memory it's always slower 'cause vba has to re-check if the object has been instantiated.)
Dim acc As Access.Application: Set acc = New Access.Application
2a) Qualify your calls to CurrentDb
acc.CurrentDb.TableDefs(myValue).Fields("F4").Properties!ColumnWidth = 2500
acc.CurrentDb.TableDefs(myValue).Fields("F7").Properties!ColumnWidth = 2500
2b) Even better, explicitly reference each of the objects in the tree [this will help with begugging]
' add Reference to "Microsoft DAO 3.6 Object Library"
Dim db As DAO.Database
Dim tdf As DAO.TableDef
Set db = acc.CurrentDb
db.TableDefs.Refresh ' CurrentDb should do this, but can't hurt
Set tdf = db.TableDefs(myValue)
With tdf
.Fields("F4").Properties!ColumnWidth = 2500
.Fields("F7").Properties!ColumnWidth = 2500
End With
Set tdf = Nothing
Set db = Nothing
I hope that this helps,
GraemeR
I am trying to run an Access Macro from Excel. I set a reference to Microsoft Office 14.0 Access database engine Object Library. Now, I'm trying to run a small script like this.
Sub RunAccessMacro()
Dim strDatabasePath As String
Dim PathToDB As String
Dim db As DAO.Database
Dim rs As DAO.Recordset
PathOfDatabase = ThisWorkbook.Worksheets("Updates").Range("PathToAccess")
Set db = DAO.DBEngine.OpenDatabase(PathOfDatabase)
Set qry = db.Execute("Macro_Run_Key")
qry.Close
db.Close
MsgBox "Done! All processes complete!!"
End Sub
The problem is, the db.Execute won't execute the Macro. I don't even see anything like RunMacro, or whatever it's called.
There must be a way to do this, right.
The database engine only does database things (anything with tables and queries). If you want more than that, you will have to use the Access application through VBA:
Sub RunAccessMacro()
Dim strDatabasePath As String
Dim PathToDB As String
Dim accApp As Access.Application
Set accApp = New Access.Application
PathOfDatabase = ThisWorkbook.Worksheets("Updates").Range("PathToAccess")
accApp.OpenCurrentDatabase PathOfDatabase
accApp.DoCmd.RunMacro "Macro_Run_Key"
accApp.Quit
Set accApp = Nothing
MsgBox "Done! All processes complete!!"
End Sub
Also, you will need to add a reference to the Microsoft Access Object Library, or you can adapt this code to use late bindings.
Setting a reference to the Access Object Library is useless unless you actually use it :) Seriously, the code written above uses DAO which is a different animal than calling Access directly through the Object Libary. DAO is strictly a database engine (like ADO) and does not know about macros and modules and such as defined in Office Apps.
Here is the code to use when using early binding:
Sub RunAccessMacro()
Dim PathOfDatabase As String
PathOfDatabase = ThisWorkbook.Worksheets("Updates").Range("PathToAccess")
Dim accApp As Access.Application
Set accApp = New Access.Application
With accApp
.OpenCurrentDatabase PathOfDatabase
.DoCmd.RunMacro "Macro_Run_Key"
.Quit
End With
MsgBox "Done! All processes complete!!"
End Sub
If the macro is an Access Macro, you can actually trigger the macro with a single command rather than having to go around the houses. The /X command line switch will help - check this link: How can I schedule a Macro to run automatically in Access 2007
I'm trying to run Access DB queries in Excel, but facing problem.
Dim dbs As DAO.Database
Set dbs = CurrentDb
dbs.Execute "DELETE FROM tblMyTable WHERE Bad", dbFailOnError
here it's getting
run time error 424 object required
exactly on the 2ndline
set dbs = CurrentDb
I already added reference DAO 3.6 object library. what to keep in place of CurrentDB. My MsAccess DB is in local disk.
CurrentDb isn't recognized by Excel, so it's being treated as an empty variant, since you haven't assigned it anything. Using Option Explicit will prevent this sort of problem in the future.
If your DB is already open, try something like: Set dbs = GetObject(,"Access.Application").CurrentDb
Option Explicit '### This goes at the VERY TOP of ALL MODULES
Sub foo()
Dim dbs As DAO.Database
Dim appAccess as Object '# Access.Application
Set appAccess = GetObject(,"Access.Application") '# Get a handle on Access
Set dbs = appAccess.CurrentDb
dbs.Execute "DELETE FROM tblMyTable WHERE Bad", dbFailOnError
End Sub
Hi guys i am new here and i am new to vba.
i want to solve the following problem:
i have two different access tables. each of them contains data i want to compare first and then, if a certain constraint is true i want to import certain columns out of one of the two access db tables into an excel sheet.
what i already have: the connection to the databases, i can read the data and print them on the console via debug.print command.
i have really no idea how to write certain rows (those which conform to the constraint) to the excel sheet.
Code sample
'commandstring and data base variables stands here
'non database connection variables
Dim oldID, newID, oldBuildPlanned, newBuildPlanned As String
Dim createExcel, doesExcelExist As Boolean
Dim xl As Excel.Application
Dim wb As Excel.Workbook
Dim Wksht As Excel.Worksheet
Dim dataVar As String
Dim counter As Integer
counter = 0
createExcelSheet = False
doesSheetExist = False
'Debug.Print "TEST old database"
Do While Not objRs.EOF And Not objRs2.EOF
'Debug.Print vbTab & objRs(0) & " " & objRs(1)
'assigning database values to variables to make them comparable
oldID = objRs(counter)
newID = CStr(objRs2(counter))
oldBuildPlanned = objRs(counter + 1)
newBuildPlanned = objRs2(counter + 1)
If oldID = newID And oldBuildPlanned = newBuildPlanned Then
createExcel = True
If createExcelSheet = True And Not doesSheetExist = True Then
Set xl = New Excel.Application
Set wb = xl.Workbooks.Add
Set Wksht = ActiveWorkbook.Worksheets("Sheet1")
doesExcelExist = True
End If
Call writeReport(newID)
End If
objRs.MoveNext
objRs2.MoveNext
Loop
'tidy up stuff comes here
end of code
I am sorry if my code is not formatted as its usual, its my first post in this forum ^^
So the writeReport() should contain the code to write the data into the sheet. i planned to insert the id's of the matching database entries into the method as parameters and read these certain data out of the recordset. but i cannot convert recordset items to string, so the byRef parameter declaration causes a compile error "type mismatch". In addition i tried to export the table with DoCmd.TransferSpreadsheet, but this method exports the entire table into excel, it worked, but it is not what i am searching for.
i hope someone can help me with my little low level problem, if you need further information feel free to ask me. i am using ADO.
Thanks in advance
Welcome to the forum,
I think you might find these two websites helpful for what you are trying to do. The first one is a great tutorial on using Access and Excel together.
http://www.datawright.com.au/excel_resources/excel_access_and_ado.htm
http://www.w3schools.com/sql/default.asp
I am not sure how you are creating your recordset, by I would recommend using an SQL statement as your source. That way you only pull the data from Access that you need. If you have any more specific questions, please let me know.
Jason