How do I update a MS Access database using excel power query? - excel

I have a quick question. So I stored all the database in access (which is local) and then I use excel's power query to import the data from access. But I want whatever changes made in excel spreadsheet (That I imported information from access) to be made in access directly using power query? Is there any way?
Thanks in advance!

I don't think this is a good idea, but you could try something like this concept.
Sub ImportFromAccess()
Dim conn As ADODB.Connection
Dim myRecordset As ADODB.Recordset
Dim strConn As String
strConn = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" & "C:\your_path_here\Northwind.mdb"
Set myRecordset = New ADODB.Recordset
FocusRow = ActiveCell.Row
With myRecordset
.Open "SELECT * FROM PersonInformation WHERE ID=" & Worksheets("Sheet1").Range("A2").Value, _
strConn, adOpenKeyset, adLockOptimistic
' This assumes that ID is a number field. If it is a text field, use
' .Open "SELECT * FROM PersonInformation WHERE ID='" & Worksheets("Sheet1").Range("A2").Value & "'", _
strConn, adOpenKeyset, adLockOptimistic
.Fields("ID").Value = Worksheets("Sheet1").Range("A" & FocusRow).Value
.Fields("FName").Value = Worksheets("Sheet1").Range("B" & FocusRow).Value
.Fields("LName").Value = Worksheets("Sheet1").Range("C" & FocusRow).Value
.Fields("Address").Value = Worksheets("Sheet1").Range("D" & FocusRow).Value
.Fields("Age").Value = Worksheets("Sheet1").Range("E" & FocusRow).Value
.Update
.Close
End With
Set myRecordset = Nothing
Set conn = Nothing
End Sub
AND
Sub UpdateRecordsInAccess()
Dim rng As Range
Dim r As Long
Dim conn As ADODB.Connection
Dim strConn As String
Dim strSQL As String
strConn = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" & _
"C:\your_path_here\Northwind.mdb"
Set conn = New ADODB.Connection
conn.Open strConn
With Worksheets("Sheet1")
lastrow = .Range("A2").End(xlDown).Row
lastcolumn = .Range("A2").End(xlToRight).Column
Set rng = .Range(.Cells(lastrow, 1), .Cells(lastrow, lastcolumn))
End With
'therow = 1
For i = 2 To lastrow
'r = rng.Row
'If r > 1 Then
strSQL = "UPDATE PersonInformation SET " & _
"FName='" & Worksheets("Sheet1").Range("B" & i).Value & "', " & _
"LName='" & Worksheets("Sheet1").Range("C" & i).Value & "', " & _
"Address='" & Worksheets("Sheet1").Range("D" & i).Value & "', " & _
"Age=" & Worksheets("Sheet1").Range("E" & i).Value & " WHERE " & _
"ID=" & Worksheets("Sheet1").Range("A" & i).Value
conn.Execute strSQL
'End If
'r = r + 1
Next i
conn.Close
Set conn = Nothing
End Sub

Sub UpdateRecordsInAccess()
Dim rng As Range
'Dim r As Long
Dim conn As ADODB.Connection
Dim strConn As String
Dim strSQL As String
strConn = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\Users\username\Desktop\DatabaseResplann.mdb;"
Set conn = New ADODB.Connection
conn.Open strConn
With Worksheets("Sheet1")
lastrow = .Range("A2").End(xlDown).Row
lastcolumn = .Range("A2").End(xlToRight).Column
Set rng = .Range(.Cells(lastrow, 1), .Cells(lastrow, lastcolumn))
End With
'therow = 1
For i = 2 To lastrow
'r = rng.Row
'If r > 1 Then
strSQL = "UPDATE Allocation SET " & _
"Resource Name='" & Worksheets("Sheet1").Range("B" & i).Value & "', " & _
"Child PID='" & Worksheets("Sheet1").Range("C" & i).Value & "', " & _
"Fct wk#='" & Worksheets("Sheet1").Range("D" & i).Value & "', " & _
"Fct Hrs='" & Worksheets("Sheet1").Range("E" & i).Value & "', " & _
"Fct %='" & Worksheets("Sheet1").Range("F" & i).Value & "', " & _
"Comment='" & Worksheets("Sheet1").Range("G" & i).Value & " WHERE " & _
"Resource ID='" & Worksheets("Sheet1").Range("A" & i).Value
conn.Execute strSQL
'End If
'r = r + 1
Next i
conn.Close
Set conn = Nothing
End Sub

Related

ACCESS file connection from EXCEL to SharePoint (SQL database)

I have an access connection file (.accdb) that allows me to use EXCEL (Office 365) to query a SharePoint Library. It all works great EXCEPT for new files added to that SharePoint Library. I can query for and return all data for these new files/entries but cannot get the filename for these new entries for some reason. Any help would be most appreciated.
Const SQLIMSSHAREPOINTCONNECTION = "Provider=Microsoft.ACE.OLEDB.12.0; Data Source = C:\MORGAN\MACROS\IMS_SHAREPOINT_db.accdb"
Sub routine:
Dim i As Long
Dim cn As Object
Dim rs As Object
Dim StrSql As String
Dim thePieces1() As String
Dim thePieces2() As String
Dim theFullFilename As String
Dim theShortFilename As String
StrSql = "SELECT [Name], [ID], [PartNumber(s)], [DateCompleted], [DocumentType], " & _
"[WorkOrder(s)], [PurchaseOrder(s)], [SalesOrder(s)], [CustomerName(s)], [WorkCenter]" & _
" FROM [Inspection Reports]"
Set cn = CreateObject("ADODB.Connection")
cn.Open SQLIMSSHAREPOINTCONNECTION
Set rs = CreateObject("ADODB.RECORDSET")
rs.ActiveConnection = cn
rs.Open StrSql
If Not (rs.BOF And rs.EOF) Then
i = 1
On Error Resume Next
Do While Not rs.EOF
i = i + 1
theFullFilename = ""
theShortFilename = ""
ReDim thePieces1(10)
thePieces1 = Split(rs.Fields(0), "#")
theFullFilename = thePieces1(1)
thePieces1() = Split(theFullFilename, "/")
theShortFilename = thePieces1(UBound(thePieces1))
Range("A" & i).Value = rs.Fields(1) ' ID
Range("B" & i).Value = theShortFilename ' Filename
Range("C" & i).Value = rs.Fields(2) ' PartNumber(s)
Range("D" & i).Value = rs.Fields(3) ' DateCompleted
Range("E" & i).Value = rs.Fields(4) ' DocumentType
Range("F" & i).Value = rs.Fields(5) ' WorkOrder(s)
Range("G" & i).Value = rs.Fields(6) ' PurchaseOrder(s)
Range("H" & i).Value = rs.Fields(7) ' CustomerName
Range("I" & i).Value = rs.Fields(8) ' WorkCenter
rs.MoveNext
Loop
It's not clear to me how your sharepoint access Excel connection works, but your recordset (rs) probably needs a refresh or requery after you updated the sharepoint data.

Delimiter in VBA,Macros

Need to split the 3rd row and have it in the below xml format.
My Excel data:
ID
EMail
UserGroupID
Aravind
Aravind#gmail.com
Sports(12-34)
Aravind2
Aravind2#gmail.com
Sports(3-24-5),Health(5-675-85), Education(57-85-96)
My XML data:
<?xml version="1.0" encoding="utf-8"?>
<Core-data ContextID="Context1" WorkspaceID="Main">
<UserList>
<User ID="Aravind" ForceAuthentication="false" Password="1234" EMail="Aravind#gmail.com">
<Name>Aravind</Name>
<UserGroupLink UserGroupID="12-34"/>
</User>
<User ID="Aravind2" ForceAuthentication="false" Password="1234" EMail="Aravind#gmail.com">
<Name>Aravind2</Name>
<UserGroupLink UserGroupID="3-24-5"/>
<UserGroupLink UserGroupID="5-675-85"/>
<UserGroupLink UserGroupID="57-85-96"/>
</User>
</UserList>
</Core-data>
The code Im using:(Need change in delimiting the 3 rd row & location only)
Sub Generate_xml()
Const FOLDER = "C:\Temp\"
Const XLS_FILE = "UserDataEntry.xlsm"
Const XML_FILE = "User XML.xml"
Const XML = "<?xml version=""1.0"" encoding=""utf-8""?>" & vbCrLf & _
"<Core-data ContextID=""Context1"" WorkspaceID=""Main"">" & vbCrLf & _
" <UserList>" & vbCrLf
Dim wb As Workbook, ws As Worksheet, ar, s As String
Dim iLastRow As Long, r As Long, n As Integer
' open source workbook
Set wb = Workbooks.Open(FOLDER & XLS_FILE, 1, 1)
Set ws = wb.Sheets("Sheet1")
iLastRow = ws.Cells(Rows.Count, "A").End(xlUp).Row
' create XML document
'<User ID="Aravind" ForceAuthentication="false" Password="1234" EMail="Aravind#gmail.com.com">
' <Name>Aravind</Name>
' <UserGroupLink UserGroupID="Sports"/>
'</User>
s = XML
For r = 2 To iLastRow
s = s & " <User ID=""" & ws.Cells(r, 1) & """" & _
" ForceAuthentication=""false"" Password=""1234""" & _
" EMail=""" & ws.Cells(r, 2) & """>" & vbCrLf
s = s & " <Name>" & ws.Cells(r, 1) & "</Name>" & vbCrLf
ar = Split(ws.Cells(r, 3), ",")
For n = LBound(ar) To UBound(ar)
s = s & " <UserGroupLink UserGroupID=""" & Trim(ar(n)) & """/>" & vbCrLf
Next
s = s & " </User>" & vbCrLf
Next
s = s & " </UserList>" & vbCrLf & "</Core-data>"
' save
Dim fso, ts
Set fso = CreateObject("Scripting.FileSystemObject")
Set ts = fso.createtextfile(FOLDER & XML_FILE)
ts.write s
ts.Close
MsgBox "Xml created to " & FOLDER & XML_FILE
End Sub
Is there is any way to run this VBA code in any location and the XML generated to be in same location.
Kindly share your inputs & thanks in advance.
Try something like this:
Sub Generate_xml()
Const FOLDER = "C:\Temp\"
Const XLS_FILE = "UserDataEntry.xlsm"
Const XML_FILE = "User XML.xml"
Const XML = "<?xml version=""1.0"" encoding=""utf-8""?>" & vbCrLf & _
"<Core-data ContextID=""Context1"" WorkspaceID=""Main"">" & vbCrLf & _
" <UserList>" & vbCrLf
Dim wb As Workbook, ws As Worksheet, s As String, savePath As String
Dim r As Long, e
' open source workbook
Set wb = Workbooks.Open(FOLDER & XLS_FILE, 1, 1)
Set ws = wb.Sheets("Sheet1")
' create XML document
s = XML
For r = 2 To ws.Cells(Rows.Count, "A").End(xlUp).Row
s = s & " <User ID=""" & ws.Cells(r, 1) & """" & _
" ForceAuthentication=""false"" Password=""1234""" & _
" EMail=""" & ws.Cells(r, 2) & """>" & vbCrLf
s = s & " <Name>" & ws.Cells(r, 1) & "</Name>" & vbCrLf
For Each e In TextInParentheses(ws.Cells(r, 3).Value)
s = s & " <UserGroupLink UserGroupID=""" & Trim(e) & """/>" & vbCrLf
Next e
s = s & " </User>" & vbCrLf
Next
s = s & " </UserList>" & vbCrLf & "</Core-data>"
'wb.Close false 'close source workbook
' save to same path as running code
savePath = ThisWorkbook.Path & "\" & XML_FILE
PutContent savePath, s
MsgBox "Xml created at '" & savePath & "'", vbInformation
End Sub
'all texts enclosed in parentheses as a collection
Function TextInParentheses(txt As String)
Dim re As Object
Dim allMatches, m, col As New Collection
Set re = CreateObject("VBScript.RegExp")
re.Pattern = "\(([^\)]+)\)"
re.ignorecase = True
re.Global = True
Set allMatches = re.Execute(txt)
For Each m In allMatches
col.Add Trim(m.submatches(0))
Next m
Set TextInParentheses = col
End Function
'Save text `content` to a text file at `f`
Sub PutContent(f As String, content As String)
CreateObject("scripting.filesystemobject"). _
opentextfile(f, 2, True).write content
End Sub

Excel Data to XML

Need to convert excel data into XML format.
'vba code to convert excel to xml
Sub vba_code_to_convert_excel_to_xml()
Set wb = Workbooks.Open("C:\temp\testwb.xlsx")
wb.SaveAs fileName:="C:\temp\testX.xml", FileFormat:= _
xlXMLSpreadsheet, ReadOnlyRecommended:=False, CreateBackup:=False
Kindly let me how to do this in VBA or provide a link where I can refer. Thanks in Advance.
For a simple case one way would be to build the xml line by line
Sub vba_code_to_convert_excel_to_xml2()
Const FOLDER = "C:\temp\"
Const XLS_FILE = "testwb.xlsx"
Const XML_FILE = "testX.xml"
Const XML = "<?xml version=""1.0"" encoding=""utf-8""?>" & vbCrLf & _
"<Core-Information ContextID=""Context1"" WorkspaceID=""Main"">" & vbCrLf & _
" <UserList>" & vbCrLf
Dim wb As Workbook, ws As Worksheet, ar, s As String
Dim iLastRow As Long, r As Long, n As Integer
' open source workbook
Set wb = Workbooks.Open(FOLDER & XLS_FILE, 1, 1)
Set ws = wb.Sheets("Sheet1")
iLastRow = ws.Cells(Rows.Count, "A").End(xlUp).Row
' create XML document
'<User ID="Aravind" ForceAuthentication="false" Password="1234" EMail="Aravind#gmail.com">
' <Name>Aravind</Name>
' <UserGroupLink UserGroupID="Sports"/>
'</User>
s = XML
For r = 2 To iLastRow
s = s & " <User ID=""" & ws.Cells(r, 1) & """" & _
" ForceAuthentication=""false"" Password=""" & ws.Cells(r, 2) & """" & _
" EMail=""" & ws.Cells(r, 3) & """>" & vbCrLf
s = s & " <Name>" & ws.Cells(r, 1) & "</Name>" & vbCrLf
ar = Split(ws.Cells(r, 4), ",")
For n = LBound(ar) To UBound(ar)
s = s & " <UserGroupLink UserGroupID=""" & Trim(ar(n)) & """/>" & vbCrLf
Next
s = s & " </User>" & vbCrLf
Next
s = s & " </UserList>" & vbCrLf & "</Core-Information>"
' save
Dim fso, ts
Set fso = CreateObject("Scripting.FileSystemObject")
Set ts = fso.createtextfile(FOLDER & XML_FILE)
ts.write s
ts.Close
MsgBox "Xml created to " & FOLDER & XML_FILE
End Sub

VBA Update statement for SQL getting Error 91 Object variable or With Block

I have been writing a VBA update for SQL and running into the error 91. It's happening on this line cmd_ADO.CommandText = SQLQuery.
Private Sub Import_Click()
Dim cn_ADO As ADODB.Connection
Dim cmd_ADO As ADODB.Command
Dim Dbconn As String
Dim SQLQuery As String
Dim strWhere As String
'Dim strStatus As String
Dim i As Integer
Dim j As Integer
Dim jOffset As Integer
Dim iStartRow As Integer
'Dim istep As Integer
'Data Columns
Dim strBusinessEntityID As String
Dim strTitle As String
Dim strFirstName As String
Dim strMiddleName As String
Dim strLastName As String
Dim strSuffix As String
jOffset = 4
iStartRow = 9
i = iStartRow
Dbconn = "Provider=SQLOLEDB;Data Source=ANF-M2MCLIENT;Initial Catalog=AdventureWorks2008R2;Integrated Security=SSPI;"
Set cn_ADO = New ADODB.Connection
cn_ADO.Open Dbconn
While Cells(i, jOffset).Value <> ""
strBusinessEntityID = Cells(i, 0 + jOffset).Value
strTitle = Cells(i, 1 + jOffset).Value
strFirstName = Cells(i, 2 + jOffset).Value
strMiddleName = Cells(i, 3 + jOffset).Value
strLastName = Cells(i, 4 + jOffset).Value
strSuffix = Cells(i, 5 + jOffset).Value
strWhere = "BusinessEntityID = " & strBusinessEntityID
'Update Statement
SQLQuery = "update Person.Person " & _
"set " & _
"Title = '" & strTitle & "', " & _
"FirstName = '" & strFirstName & "' " & _
"MiddleName = '" & strMiddleName & "' " & _
"LastName = '" & strLastName & "' " & _
"Suffix = '" & strSuffix & "' " & _
"where " & strWhere
cmd_ADO.CommandText = SQLQuery
cmd_ADO.ActiveConnection = cn_ADO
cmd_ADO.Execute
i = i + 1
Wend
Set cmd_ADO = Nothing
Set cn_ADO = Nothing
End Sub
cmd_ADO is declared but not initialized. Change the declaration line to:
Dim cmd_ADO As New ADODB.Command
Notice the addition of the New keyword.
See here for details on creating and executing a command.
In addition:
You would have errors with your SQL query string; you don't have the commas in the where you should. For example, it should be:
"FirstName = '" & strFirstName & "', "
Add the commas as you did for Title.
You're not initialising the command object, only the connection object.
Try adding in the line:
Set cmd_ADO = New ADODB.Command
Here is a link to the Microsoft documentation that explains the error in more detail.

VBA error 462 when updating table in Access from Excel

I'm getting the 462 runtime error when updating an Access table from Excel VBA. I think the references are correctly qualified with the object variable as described here and here, but I'm still getting an error on the line where the number of records is assigned to dbImageCount using DCount.
Run-Time error '462': The remote server machine does not exist or is unavailable
Public AppAccess As Access.Application
...
Sub btnSave2Access_Click()
Dim MyRow As Long, LastCaptionRow As Integer
Dim sPath As String, STblName As String, CatalogNum As String, LotNum As String
Dim i As Integer, dbImageCount As Integer
CatalogNum = Trim(Sheets("Tier2Worksheet").Range("B2"))
LotNum = Trim(Sheets("Tier2Worksheet").Range("B3"))
LastCaptionRow = Range("E1000").End(xlUp).Row
sPath = Sheets("Settings").Range("B16")
STblName = "tblProductPictures"
Set AppAccess = New Access.Application
With AppAccess
.OpenCurrentDatabase sPath
For i = 1 To LastCaptionRow
'error in next line
dbImageCount = DCount("[SortOrder]", STblName, "[CatalogNum] = '" & CatalogNum & "' AND [LotNum] = '" & LotNum & "'") 'get current image count in DB for catNum/LotNum combo
While dbImageCount < LastCaptionRow 'adds record to picture table when required
dbImageCount = dbImageCount + 1
.DoCmd.RunSQL "INSERT INTO " & STblName & " (CatalogNum, LotNum, SortOrder) VALUES ('" & CatalogNum & "','" & LotNum & "','" & dbImageCount & "');"
DoEvents
Wend
With .DoCmd
.SetWarnings False
.RunSQL "UPDATE " & STblName & " SET PicPath='" & Range("E" & i) & "' Where [CatalogNum]='" & CatalogNum & "' and [SortOrder]='" & i & "' and [LotNum]='" & LotNum & "';"
.RunSQL "UPDATE " & STblName & " SET FullCaption='" & Range("D" & i) & "' Where [CatalogNum]='" & CatalogNum & "' and [SortOrder]='" & i & "' and [LotNum]='" & LotNum & "';"
.SetWarnings True
End With
Next i
.CloseCurrentDatabase
.Quit
End With
Set AppAccess = Nothing
Application.StatusBar = False
End Sub
Manually setting the value of dbImageCount on the fly during debug (commenting out the DCount line) properly updates the database with the new picture data.
It's important to note that this problem does not occur consistently. After months of use, the error did not creep up until this week and even then it didn't happen for every update attempt. In addition, it never happened during development (on a different system).
At first, I thought it was a network glitch or something of the like, but then I read that the 426 error is specifically an Office automation problem, so I expect that we will see it again soon.
You need to use DCount as a method of the Access Application:
With AppAccess
.OpenCurrentDatabase sPath
For i = 1 To LastCaptionRow
'error in next line
dbImageCount = .DCount("[SortOrder]", STblName, "[CatalogNum] = '" & CatalogNum & "' AND [LotNum] = '" & LotNum & "'") 'get current image count in DB for catNum/LotNum combo
While dbImageCount < LastCaptionRow 'adds record to picture table when required
dbImageCount = dbImageCount + 1
.DoCmd.RunSQL "INSERT INTO " & STblName & " (CatalogNum, LotNum, SortOrder) VALUES ('" & CatalogNum & "','" & LotNum & "','" & dbImageCount & "');"
DoEvents
Wend
With .DoCmd
.SetWarnings False
.RunSQL "UPDATE " & STblName & " SET PicPath='" & Range("E" & i) & "' Where [CatalogNum]='" & CatalogNum & "' and [SortOrder]='" & i & "' and [LotNum]='" & LotNum & "';"
.RunSQL "UPDATE " & STblName & " SET FullCaption='" & Range("D" & i) & "' Where [CatalogNum]='" & CatalogNum & "' and [SortOrder]='" & i & "' and [LotNum]='" & LotNum & "';"
.SetWarnings True
End With
Next i
.CloseCurrentDatabase
.Quit
End With

Resources