VBA - Update Linked Table of an Access file from Excel - excel

I am trying to change the linked table address from an Access file "Hey.accdb" using VBA coding from an Excel file.
I've coded the script below in my Excel file and it prompts the error "Object required" when I run it. Can someone please help me with this problem. I've been staring at it for too long. Thanks.
Sub RunMacroinAccesswithPara2()
Set Db = CreateObject("Access.Application")
Db.OpenCurrentDatabase "D:\Database1\Hey.accdb"
Db.Visible = True
Db.AutomationSecurity = msoAutomationSecurityLow
DoCmd.TransferDatabase TransferType:=acLink, _
DatabaseType:="Microsoft Access", _
DatabaseName:="V:\Reporting\Quarterly\2018Q2\JP\Data\04\Database\Valuation_Database.mdb", _
ObjectType:=acTable, _
Source:="Valuation_Database_Adjusted", _
Destination:="Valuation_Database_Adjusted"
End Sub

DoCmd belongs to the Access application object.
So use
Db.DoCmd.TransferDatabase ' etc.
Edit
To update the link, you need the TableDef object, set its .Connect property and run .RefreshLink.
See Linked table ms access 2010 change connection string

Related

Excel Queries from Excel Workbook located on OneDrive From Different Users

Friends,
I currently am pulling data from an excel file located in OneDrive into my spreadsheet using the following source.
= Excel.Workbook(File.Contents("C:\Users\Bob Saggat\OneDrive - USS Enterprise\Prototype\InvestorsMasterProto.xlsm"), null, true)
I use the following code to successfully post data to files with different users from the OneDrive folder in VBA modules with the following code:
Workbooks.Open("C:\Users\" & Environ("username") & "\OneDrive - USS Enterprise\Prototype\OrdersMasterProto.xlsm")
I expected using Environ("username") in the Power Query Editor in the code for the source of the file to work.
= Excel.Workbook(File.Contents("C:\Users\" & Environ("username") & "\OneDrive - USS Enterprise\Prototype\InvestorsMasterProto.xlsm"), null, true)
When I do so I get the following error: Expression.Error: The name 'Environ' wasn't recognized. Make sure it's spelled correctly.
What is the solution here?
Some GoogleFu suggests I host the file on a SharePoint instead of in OneDrive but I have absolutely no experience in SharePoint and I presume there is a simple solution I am missing.
As always, your wisdom and kindness is greatly appreciated.
Thank You
--
Now, I call this module on load to find the username and put it into a named ranged. This works.
Sub GetUsernameForDataSource()
Dim OrderRunTemplate As Worksheet
Set OrderRunTemplate = ThisWorkbook.Worksheets("Order Run Template")
LocalUsername = Environ("username")
'May need to clear the CurrentUser named ranged first then add the user so it doesn't add multiple users
'Adding LocalUsername to named range to use as source in PowerQuery
ThisWorkbook.Names.Add Name:="CurrentUser", _
RefersTo:=LocalUsername
End Sub
Yet when I go into PowerQuery and enter the following
= Excel.Workbook(File.Contents("C:\Users\" & Excel.CurrentWorkbook(){[Name="CurentUser"]}[Content]{0}[Column1] & "\OneDrive - USS Enterprise\Prototype\InvestorsMasterProto.xlsm"), null, true)
I get the error:
Expression.Error: We couldn't find an Excel table named 'CurrentUser'.
Details:
CurrentUser
Any suggestions?
assuming you can get the value of Environ("username") into a named range such as abc, then you can read that named range in powerquery using
Excel.CurrentWorkbook(){[Name="abc"]}[Content]{0}[Column1]
and in your code as
= Excel.Workbook(File.Contents("C:\Users\" & Excel.CurrentWorkbook(){[Name="abc"]}[Content]{0}[Column1] & "\OneDrive - USS Enterprise\Prototype\InvestorsMasterProto.xlsm"), null, true)

Access Type conversion failure importing from Excel

I'm trying to import an Excel to Access DB, and some customer numbers cannot be imported due to Type Conversion Failure. It is 12 entries out of 66 thousand. Normally the customer number is a number, but these 12 are strings like ABCDEFT001. I tried setting the field of the table to Long Text or Short text, they are still not imported (only to ImportError table). Do you know what else I can try?
Thank you very much in advance!
P.S. I'm trying to import using DoCmd.TransferSpreadsheet
DoCmd.TransferSpreadsheet acImport, acSpreadsheetTypeExcel12Xml, "Inv level", "Path/to/file.xlsb", True, "Sheetname!"
This strategy links to the excel file, instead of directly importing it, and then selects data out of it and casts any fields that need it to the correct datatype.
Sub ImportFromExcel()
Dim pathToFile As String
Dim targetTableName As String
Dim sql As String
pathToFile = "C:\Path\To\File.xlsx"
targetTableName = "ImportResults"
'//create the link
DoCmd.TransferSpreadsheet acLink, _
acSpreadsheetTypeExcel12, _
targetTableName, _
pathToFile, _
True '//This part only if the excel file has field headers
'//import
sql = "SELECT Field1Name, CStr(CustNumber) AS CustNumber, Field3Name INTO NewImportTable FROM " & targetTableName
CurrentDb.Execute sql
'//remove the link
DoCmd.DeleteObject acTable, targetTableName
End Sub
***Two pitfalls of this code to be aware of:
1) You should delete any table with the name "NewImportTable" before running this code, or you'll get a "Table Already Exists" error.
2) If any errors happen in this Sub before you remove the link, you'll have an issue the next time it runs, as it will create a link called "ImportResults1" since "ImportResults" would still exist. The really scary thing is that no errors would be thrown here. It would create "ImportResults1" and then run your sql on "ImportResults"!!

Excel VBA AccessApplication.OpenCurrentDatabase Not Working

Here is what I'm trying to do with Excel VBA:
Copy a range in Excel
Open an Access database
Delete records from the CV table
Paste the new records from Excel into the CV table
Run a make table query
Close the database
The code below worked - once. After it ran successfully once, it will not run again. There is no error message - the Access DB just never opens and the macro ends. Nothing ran behind the scenes, the Access DB was never touched.
I am speculating that the error might have to do with the fact that the application was opened once and maybe not closed properly and therefore can't reopen? (No idea if this is accurate/makes sense)
Sheets("NAHVCV").Select
Range("A:C").Select
Selection.Copy
Dim appAccess As New Access.Application
Set appAccess = Access.Application
appAccess.OpenCurrentDatabase AccessDBPath
appAccess.Visible = True
appAccess.CurrentDb.Execute "DELETE * FROM [CV]"
appAccess.DoCmd.OpenTable "CV", acViewNormal, acEdit
appAccess.DoCmd.RunCommand acCmdPasteAppend
appAccess.DoCmd.Close acTable, "CV", acSaveYes
appAccess.DoCmd.OpenQuery "qryMakFutRetroVariance"
appAccess.CloseCurrentDatabase
appAccess.Quit acQuitSaveAll
Maybe define the access application above/outside the sub:
Dim appAccess As New Access.Application
Sub Test()
'Add the rest of your code
End Sub
I had a similar problem to yours but once I moved the access application out of the sub, my access file opened up every time
Referring to your questions, Ashley, I distinguish
How to open Ms Access Database from Excel VBA (but not necessery for point 2)
Update data in Ms Access table CV from Excel VBA
Ad 1.:
To open an Access Database via method .OpenCurrentDatabase from Excel application VBA, select - with early binding - in Tools|References the library "Microsoft Access 16.0 Object Library" (V16.0 = Office 365).
After some tries, I understood that the opened Access Application, created by
Set apAccess = New Access.Application
is still linked to this object 'apAccess' created at runtime and is destoyed on ending Sub/Function, hence the object required to be defined globaly at VBA Module top, outside any Sub/Function (thanks, Brendon for the hint!) to 'remain alive' after Sub/Function ending:
Option Explicit,
Dim apAccess as Access.Application
Sub OpenAccessApp(sAccessPathFile as String)
Set apAccess = New Access.Application 'instantiate global defined Access object
appAccess.OpenCurrentDatabase(sAccessPathFile)
apAccess.Visible = True
End Sub
Do not destroy object 'apAccess' via Set apAccess = Nothing - this will close Ms Access DB!
Ad 2.:
To update records in another Ms Access database - from Excel VBA - you don't need to open the Access data base Window, as shown in Ad 1. above, but just use Access 'build-in' DAO objects; this requires linking Excel to Access database engine library (Tools|References, select library "Microsoft Access 16.0 database engine Object Library" - NOT "Microsoft Access 16.0 Object Library", mentioned above in Ad 1.); alternatively you can also process with ADODB (which requires a reference to another library), but below, I refer to DAO-object and -method, run in an Excel Project:
Sub UpdateAccData(sDBPathFileName as String) 'Parameter includes external Access Path\Filename
Dim db as DAO.Database 'define DAO object, only works when referencing to database engine library!
Set db = DBEngine.Workspaces(0),OpenDatabase(sDBPathFileName) 'Instantiate DAO Database object
'Run MakeTable query to build table 'CV' by SQL via Execute method:
db.Execute "SELECT 'Value1' As Field1, 815 as Field2, #05/18/2022# as Field3 INTO CV;", dbFailOnError
'Note: Field1 becomes Short Text, Field2 = Number (Long Integer), Field3 = Date/Time
But, I would dissuade to use MakeTable queries: in order to build a new table 'CV', MakeTable destroyes existing table 'CV', before creating a new one. If your data includes corrupted fields, table 'CV' failed to be build AFTER old 'CV' was already destroyed; as old table 'CV' was deleted, table 'CV' is missing in the entity relation! If Forms or Queries refer to table 'CV', they generates error, when opened or launched. Hence, keep table 'CV' and just remove records by DELETE and add new records via "INSERT INTO" as shown below (please update fields and Value acc. your need):
'Remove records in table 'CV' by SQL via Execute method:
db.Execute "DELETE CV.* FROM CV WHERE (((CV.Field5)='Criteria'));", dbFailOnError 'omit WHERE clause, if you would empty the whole table
'AddNew/insert new records in table 'CV' with method Execute:
db.Execute "INSERT INTO CV ( Field1, Field2, Field3 ) SELECT 'Value1', 815, #05/18/2022#;", dbFailOnError
'Alternative: Update existing records in table 'CV':
db.Execute "UPDATE CV SET CV.Field1='Value1', CV.Field2=815, CV.Field3=#05/18/2022#, WHERE (((CV.Field5)='Criteria'));", dbFailOnError
End Sub

User Defined type not defined

I continue to get a user-defined error. This code is very helpful in exporting data to access. It just won't kick off because of the User-defined error.
Thank you
Public Sub AccImport()
Dim acc As DAO.Database
acc.OpenCurrentDatabase "C:\Users\public\Database1.accdb"
acc.DoCmd.TransferSpreadsheet _
acImport, _
acSpreadsheetTypeExcel12Xml, _
"tblExcelImport", _
Application.ActiveWorkbook.FullName, _
True, _
"Folio_Data_original$A1:B10"
acc.CloseCurrentDatabase
acc.Quit
Set acc = Nothing
End Sub
You should tell us which line the error refers to, but it is most likely the second.
You need to add a reference to the DAO library. Go to Tools, References and find and tick Microsoft DAO 3.6 Object Library, so that you can then use DAO. in your code.
But OpenCurrentDatabase is an Access method. To use this, and then call TransferSpreadsheet, you need to use Access Automation. This involves:
Having a Reference to the Access Object Library
Creating a new instance of the Access Application, and having an
object variable that refers to this new instance
Then you can use OpenCurrentDatabase and TransferSpreadsheet.

ADODB.Connection undefined

Reference Excel VBA to SQL Server without SSIS
After I got the above working, I copied all the global variables/constants from the routine, which included
Const CS As String = "Driver={SQL Server};" _
& "Server=****;" _
& "Database=****;" _
& "UID=****;" _
& "PWD=****"
Dim DB_Conn As ADODB.Connection
Dim Command As ADODB.Command
Dim DB_Status As Stringinto a similar module in another spreadsheet. I also copied into the same module
Sub Connect_To_Lockbox()
If DB_Status <> "Open" Then
Set DB_Conn = New Connection
DB_Conn.ConnectionString = CS
DB_Conn.Open ' problem!
DB_Status = "Open"
End If
End SubI added the same reference (ADO 2.8)
The first spreadsheet still works; the seccond at DB_Conn.Open pops up "Run-time error '-214767259 (80004005)': [Microsoft][ODBC Driver Manager] Data source name not found and no default driver specified"
Removing the references on both, saving files, re-opening, re-adding the references doesn't help. The one still works and the other gets the error.
?!?
I observed the same error message and in my case nothing had changed. I wondered if my odbc driver needed to be reinstalled (based on what i read online). In any case, restarting excel did the trick. Sometimes the solution is much simpler. :-)
When the error pops up, check your "locals" windows to see what the CS holds. View > Locals Window
Problem: Your constant isn't found by the compiler.
Solution: With the constant being located in a separate module, you'll need to set it as Public for the other code to see it.
Proof:
In order to prove this theory you can do the following:
Open a new Excel spreadsheet
Go to the VBA designer and add a new module
In this module put:
Const TestString As String = "Test String"
Then add the following code to ThisWorkbook:
Public Sub TestString()
MsgBox (TestString)
End Sub
After adding this return to the workbook and add a button, selecting "TestString" as the macro to run when clicked.
Click the button and a blank message box will appear.
Go back to the VBA designer and change the const in Module1 to Public
Click the button on the spreadsheet and you should now see "Test String" in the message box.
I realize that this question is really old. But for the record I want to document my solutions for the error here: It was a data related error in a spreadsheet! A column was formatted as date and contained a value 3000000. Changing the Format to numbers solved the Error 80004005.

Resources