Application Connect Excel sheet to Access - excel

I am stuck at below mentioned situation guide me. I have one user form i made in excel . i can try to perform crud i have completed insert. i can try to update or delete not working please give me some idea.
this is my insert code it is properly working
insert:-
Private Sub CommandButton1_Click()
Dim cn As Object
Dim strQuery As String
Dim Name As String
Dim City As String
Dim myDB As String
Dim iRow As Long
Dim ws As Worksheet
Set ws = Worksheets("Sheet1")
'Initialize Variables
Name = Me.TextBox1.Value
City = Me.TextBox2.Value
Dept = Me.ComboBox1.Value
myDB = "C:\Users\abc\Desktop\nis\ni2\em.accdb"
'Set cn = CreateObject("ADODB.Connection")
With cn
.Provider = "Microsoft.ACE.OLEDB.12.0" 'For *.ACCDB Databases
.ConnectionString = myDB
.Open
MsgBox "con created"
End With
strQuery = "INSERT INTO emp ([Name], [City],[Dept]) " & _
"VALUES (""" & Name & """, """ & City & """,""" & Dept & """); "
MsgBox "success fully insert"
cn.Execute strQuery
cn.Close
Set cn = Nothing
Me.TextBox1.Value = ""
Me.TextBox2.Value = ""
Me.ComboBox1.Value = ""
End Sub
update code:-
Dim cn As Object
Dim strQuery As String
Dim Name As String
Dim City As String
Dim myDB As String
Dim iRow As Long
Dim ws As Worksheet
Set ws = Worksheets("Sheet1")
'Initialize Variables
' Name = Me.TextBox1.Value
' City = Me.TextBox2.Value
' Dept = Me.ComboBox1.Value
myDB = "C:\Users\abc\Desktop\nis\ni2\em.accdb"
'Set cn = CreateObject("ADODB.Connection")
With cn
.Provider = "Microsoft.ACE.OLEDB.12.0" 'For *.ACCDB Databases
.ConnectionString = myDB
.Open
MsgBox "con created"
End With
strQuery = "Update emp Set [Name]='" & Me.TextBox1.Value & "',"&[City]='" & TextBox2.Value & "',&[Dept]='" & Me.ComboBox1.Value & "'"
MsgBox "success fully insert"
cn.Execute strQuery
cn.Close
Set cn = Nothing
Me.TextBox1.Value = ""
Me.TextBox2.Value = ""
Me.ComboBox1.Value = ""
End Sub

Your line
strQuery = "Update emp Set [Name]='" & Me.TextBox1.Value & "',"&[City]='" & TextBox2.Value & "',&[Dept]='" & Me.ComboBox1.Value & "'"
is attempting to update all lines in the emp table with those values. I suspect you only want to update one line. You need to add a WHERE clause to specify which line.
EDIT: Just noticed there's a syntax error in that line as well. It should read
strQuery = "Update emp Set [Name]='" & Me.TextBox1.Value & "', [City]='" & TextBox2.Value & "',[Dept]='" & Me.ComboBox1.Value & "' Where "
and then should finish with your where clause

Related

download certain tables from mysql server to particular location as csv files

connect to mysql database.
should give user input which table to download from database.
selected table should get downloaded to particular location and save as a csv file. note csv name should be tablename.csv.
Sub connect()
Dim Password As String
Dim SQLStr As String
'OMIT Dim Cn statement
Dim Server_Name As String
Dim User_ID As String
Dim Database_Name As String
'OMIT Dim rs statement
Set rs = CreateObject("ADODB.Recordset") 'EBGen-Daily
Server_Name = "localhost"
Database_Name = "testdb" ' Name of database
User = "root" 'id user or username
Password = "zxcasdQWE123" 'Password
SQLStr = "SELECT * FROM vector"
Set Cn = CreateObject("ADODB.Connection") 'NEW STATEMENT
Cn.Open "Driver={MySQL ODBC 8.0 Unicode Driver};Server=" & _
Server_Name & ";Database=" & Database_Name & _
";User=" & User & ";Password=" & Password & "; Option=3;"
rs.Open SQLStr, Cn, adOpenStatic
Dim myArray()
Dim ostream As Object
myArray = rs.GetRows()
kolumner = UBound(myArray, 1)
rader = UBound(myArray, 2)
Set ostream = CreateObject("ADODB.Stream")
ostream.Open
'ostream.WriteText "hi, hello" & vbNewLine & "how, are" ' test input. not for any use
ostream.SaveToFile ("C:\Users\asus\Downloads\vector.csv")
ostream.Close
rs.Close
Set rs = Nothing
Cn.Close
Set Cn = Nothing
End Sub
I have connected to my database and selected a table for eg and put into array. now i am struck with how to download that table as csv's. and make user input on which table to select from database.
Can anyone help me with it.
Create a new workbook, copy records to sheet using CopyFromRecordset and then save as CSV.
Option Explicit
Sub CreateCSV()
' logon credentials
Const Server_Name = "localhost"
Const Database_Name = "testdb" ' Name of database
Const User = "root" 'id user or username
Const Password = "zxcasdQWE123" 'Password
' connect
Dim Cn As Object, sCn As String, rs As Object
Set Cn = CreateObject("ADODB.Connection") 'NEW STATEMENT
Cn.Open "Driver={MySQL ODBC 8.0 Unicode Driver}" & _
";Server=" & Server_Name & ";Database=" & Database_Name & _
";User=" & User & ";Password=" & Password & "; Option=3;"
' get list of tables
Dim arTbl, n As Long, sTbl As String, msg As String, u As Variant
Set rs = Cn.Execute("SHOW TABLES")
arTbl = rs.getrows()
For n = 1 To UBound(arTbl, 2)
msg = msg & n & ") " & arTbl(0, n - 1) & vbLf
Next
u = InputBox(msg, "Select Table")
' check user input is valid
If IsNumeric(u) Then
If u < 1 Or u > UBound(arTbl, 2) Then
MsgBox u & " is an invalid entry !", vbExclamation
Exit Sub
End If
Else
MsgBox u & " is an invalid entry !", vbExclamation
Exit Sub
End If
' selected table
sTbl = arTbl(0, u - 1)
' execute query
Dim wbCSV As Workbook, wb As Workbook, filename As String
Set rs = Cn.Execute("SELECT * FROM " & sTbl)
' create workbook, save as csv
Set wb = ThisWorkbook
Set wbCSV = Workbooks.Add(1)
filename = wb.Path & "\" & sTbl & ".csv"
With wbCSV.Sheets(1)
' header
For n = 1 To rs.Fields.Count
.Cells(1, n) = rs.Fields(n - 1).Name
Next
' data
.Range("A2").CopyFromRecordset rs
n = .Cells(.Rows.Count, "A").End(xlUp).Row
.SaveAs filename, xlCSV
wbCSV.Close savechanges:=False
End With
MsgBox n - 1 & " rows exported to " & filename, vbInformation
End Sub

Load aggregate data from Excel into ADODB.RecordSet

I am trying to load data from an Excel file in a specific sheet into an ADODB.RecordSet via a VBA macro by using SQL SELECT command.
There are several columns on the Excel sheet, and I don't need all of them.
For example:
col.A = Surname, col.B = Name, col.C = IDPerson, [....columns that are not needed], Col.N = Boss
The purpose would be to get a recordset of aggregated data for:
col.C = IDPerson, col.N = Boss.
The fields highlighted in the image below.
I would like to have a RecordSet with the aggregated (non-repeating) data of the columns highlighted in yellow.
Obviously, this problem could also be solved by loading a matrix, but, in this case I would have to build a loading algorithm to "clean" any repetitions in the data and then later I would have to provide a search function with some loops.
So I thought that if I could load all the data I need by reading the WorkSheet as if it were a data table and then make a query on it to extract the data that I need and load everything in an ADODB.RecordSet would be much more efficient also for searching for data (filter data for example).
Below I report my code that loads all the data of my sheet:
Public Sub LoadRecordSet(ByVal LastRow As Long, ByVal LastCol As Integer)
Dim cnt As ADODB.Connection
Dim rsData As ADODB.Recordset
Dim strSQL As String
Dim strTMP As String
strTMP = Cells(LastRow, LastCol).Address
strTMP = Replace(strTMP, "$", "")
Set cnt = New ADODB.Connection
cnt.Mode = adModeRead
cnt.ConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0;" & _
"Data Source=" & ActiveWorkbook.FullName & ";" & _
"Extended Properties=""Excel 12.0 Macro;HDR=Yes;"";"
cnt.Open
strSQL = "SELECT * FROM [Sheet1$C2:" & strTMP & "]"
Set rsData = New ADODB.Recordset
With rsData
Set .ActiveConnection = cnt
.Source = strSQL
.CursorLocation = adUseClient
.CursorType = adOpenKeyset
.LockType = adLockOptimistic
.Open
End With
'TODO - Something with rsData for filtering or to research
'GC
If Not rsData Is Nothing Then
If rsData.State <> adStateClosed Then rsData.Close
Set rsData = Nothing
End If
If Not cnt Is Nothing Then
If cnt.State <> adStateClosed Then cnt.Close
Set cnt = Nothing
End If
End Sub
My question is: "What if I just want to load some columns as described above and aggregate them so they don't have repetitions in the data?"
For example if I want to load similar
SELECT [cod.fiscale], responsabile FROM [MySheet$A3:N480] GROUP BY [cod.fiscale], responsabile
It's possible?
Thank you so much.
I improved my code which is now working:
Public Sub CaricaDati()
Dim cnt As ADODB.Connection
Dim rsDati As ADODB.Recordset
Dim strSQL As String
Dim strTMP As String
Dim i As Integer
on Error GoTo Error_Handler
Range("A3").Select
g_BOLTS_UltimaRiga = LasRow
Call LastCol
strTMP = Cells(g_LastRow, g_LastCol).Address
strTMP = Replace(strTMP, "$", "")
Set cnt = New ADODB.Connection
cnt.Mode = adModeRead
cnt.ConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0;" & _
"Data Source=" & ActiveWorkbook.FullName & ";" & _
"Extended Properties=""Excel 12.0 Macro;HDR=Yes;"";"
cnt.Open
'strSQL = "SELECT * FROM [2$C2:" & strTMP & "]"
strSQL = "SELECT cf, responsabile FROM [2$C2:" & strTMP & "] GROUP BY cf, responsabile"
Set rsDati = New ADODB.Recordset
With rsDati
Set .ActiveConnection = cnt
.Source = strSQL
.CursorLocation = adUseClient
.CursorType = adOpenKeyset
.LockType = adLockOptimistic
.Open
End With
If Not (rsDati.BOF And rsDati.EOF) Then
strTMP = ""
For i = 0 To rsDati.Fields.Count - 1
strTMP = strTMP & rsDati.Fields(i).Name & ";"
Next i
Debug.Print strTMP
strTMP = ""
rsDati.MoveFirst
Do While Not rsDati.EOF
strTMP = ""
For i = 0 To rsDati.Fields.Count - 1
strTMP = strTMP & rsDati.Fields(i).Value & ";"
Next i
Debug.Print strTMP
rsDati.MoveNext
Loop
End If
Uscita:
On Error Resume Next
'GC
If Not rsDati Is Nothing Then
If rsDati.State <> adStateClosed Then rsDati.Close
Set rsDati = Nothing
End If
If Not cnt Is Nothing Then
If cnt.State <> adStateClosed Then cnt.Close
Set cnt = Nothing
End If
Exit Sub
Error_Handler:
On Error GoTo 0
MsgBox Err.Number & " - " & Err.Description, vbOKOnly + vbCritical, "ERRORE IMPREVISTO"
GoTo Uscita
End Sub

Getting "Automation error" while updating a column through VBA

I have written a VBA code to update a column but getting Automation Error while running the program at line 41 which is Set rsf = cmd.Execute. Is the way of writing update statement incorrect in my code? Not getting what is the issue here. I'd appreciate any help towards a solution for my problem.
Private Sub Update_Visibility_Flag_Click()
Dim fldrpath As String
Dim currDate As String
Dim mePrgTrck As String
Dim wkb1 As Workbook
Dim sht1 As Worksheet
Dim cnf As ADODB.Connection
Dim rsf As ADODB.Recordset
Dim sqlstr As String
fldrpath = "\\lp99dfd\groups$\Record Extracts\New folder\New folder\" & Format(Date, "yyyymm")
currDate = "PI_202008"
mePrgTrck = fldrpath & "\LE\Progress_Tracker_" & Format(Date, "yyyymm") & "_LE.xlsx"
Set wkb1 = Workbooks.Open(mePrgTrck)
Set sht1 = wkb1.Sheets(currDate)
Set cnf = New ADODB.Connection
Set rsf = New ADODB.Recordset
cnf.Open ( _
"User ID=AI_ZK_DTA" & _
";Password=aizkdta" & _
";Data Source=POIUY" & _
";Provider=OraOLEDB.Oracle")
For Each cell In sht1.Range("A2:A28")
If cell.Offset(0, 3).Value = "Success" Then
sqlstr = "UPDATE AI_" & cell.Value & "_DTA SET VISIBLE = 'Y'"
Dim cmd As ADODB.Command
Set cmd = New ADODB.Command
Set cmd.ActiveConnection = cnf
cmd.CommandType = adCmdText
cmd.Properties("PLSQLRSet") = True
cmd.CommandText = sqlstr
Set rsf = cmd.Execute
cmd.Properties("PLSQLRSet") = False
cell.Offset(0, 8).Value = cell.Offset(0, 8).Value & "| Done"
End If
Next cell
wkb1.Close True
Set rsf = Nothing
Set cnf = Nothing
End Sub

error: 'Application-defined or object-defined error' when using CopyFromRecordset - Excel macos

I am calling data from a PostgreSQL database into an Excel spreadsheet using the following macro:
Sub sub_copy_Recordset()
Dim objRecordset As Recordset
Dim strConnection As String
Dim input_portfolio, setRange As String
Dim end_date As Date
Dim i, record_count As Integer
input_portfolio = ActiveWorkbook.Sheets("_portfolio").Range("main").Cells(1, 1).Value
end_date = ActiveWorkbook.Sheets("_portfolio").Range("main").Cells(2, 1).Value
ini_date = ActiveWorkbook.Sheets("_portfolio").Range("main").Cells(3, 1).Value
On Error GoTo ErrHandler
strConnection = "Driver={PostgreSQL Unicode};Server=[ip];Port=5432;Database=[db];UID=user;PWD=[pwd];"
Set objConnection = New ADODB.Connection
Set objRecordset = New ADODB.Recordset
objRecordset.CursorLocation = adUseClient
objConnection.Open strConnection
With objRecordset
.ActiveConnection = objConnection
.Open "SELECT * FROM portfolio_positions('" & input_portfolio & "','" & end_date & "');"
End With
With ActiveWorkbook.Sheets("_tables")
.Range("A2").CopyFromRecordset objRecordset
record_count = objRecordset.RecordCount
objRecordset.Close
Set objRecordset = Nothing
End With
objConnection.Close
Set objConnection = Nothing
MsgBox "End Sub"
Exit Sub
ErrHandler:
Debug.Print Err.Number & " " & Err.Description
End Sub
When the macro executes the line where I copy the recordset to cell "A2" .Range("A2").CopyFromRecordset objRecordset it copies the data to A2 and jumps to the end of the Sub and executes line MsgBox "End Sub". When I add additional instructions below the CopyFromRecordset line as next:
Sub sub_copy_Recordset()
Dim objRecordset As Recordset
Dim strConnection As String
Dim input_portfolio, setRange As String
Dim end_date As Date
Dim i, record_count As Integer
input_portfolio = ActiveWorkbook.Sheets("_portfolio").Range("main").Cells(1, 1).Value
end_date = ActiveWorkbook.Sheets("_portfolio").Range("main").Cells(2, 1).Value
On Error GoTo ErrHandler
strConnection = "Driver={PostgreSQL Unicode};Server=79.143.185.46;Port=5432;Database=fincerec_canaima;UID=fincerec_user;PWD=_Or0cua1#;"
Set objConnection = New ADODB.Connection
Set objRecordset = New ADODB.Recordset
objRecordset.CursorLocation = adUseClient
objConnection.Open strConnection
With objRecordset
.ActiveConnection = objConnection
.Open "SELECT * FROM portfolio_positions('" & input_portfolio & "','" & end_date & "');"
End With
With ActiveWorkbook.Sheets("_tables")
.Range("A2").CopyFromRecordset objRecordset
record_count = objRecordset.RecordCount
objRecordset.Close
Set objRecordset = Nothing
.Columns("A").ColumnWidth = 20
.Columns("B").ColumnWidth = 5
With .Columns("C:G")
.ColumnWidth = 12
.NumberFormat = "#,##0.00"
.HorizontalAlignment = xlRight
End With
setRange = "A" & record_count + 2 & ":G1000"
.Range(setRange).ClearContents
setRange = "A2:G" & record_count + 1
.Names("_positionsRange").Delete
.Range(setRange).Name = "_positionsRange"
End With
objConnection.Close
Set objConnection = Nothing
MsgBox "End Sub"
Exit Sub
ErrHandler:
Debug.Print Err.Number & " " & Err.Description
End Sub
It copies the recordset in cell A2, but then jumps to ErrHandler: and then reports error
1004 Application-defined or object-defined error
Any help is appreciated.

Dynamic query call and connection string

Sub SavedConfiguration()
Dim cnn1 As New ADODB.Connection
Dim mrs As New ADODB.Recordset
Dim iCols As Integer
Const TABLE_NAME = "TableName"
Const DRIVER = "{SQL Server}"
Dim conf
conf = Array("D11", "database", "D12", "server")
Dim wb As Workbook, wsConfig As Worksheet, wsOut As Worksheet
Dim i As Integer, strConn As String, sQry As String
Set wb = ThisWorkbook
Set wsConfig = Worksheets("Settings")
Set wsOut = Worksheets("SavedConfig")
' construct connection string
strConn = "driver=" & DRIVER & ";"
For i = 1 To UBound(conf) Step 2
strConn = strConn & conf(i) & "=" & wsConfig.Range(conf(i - 1)).Value & ";"
Next
' Debug.Print strConn
sQry = Worksheets("SQL-COMMON").Range("B3").Value
' connect to db and run sql
Set cnnl = New ADODB.Connection
cnnl.ConnectionString = strConn
cnnl.ConnectionTimeout = 30
cnnl.Open
wsConfig.Range("H35") = Now
' output
mrs.Open sQry, cnn1
For iCols = 0 To mrs.Fields.Count - 1
wsOut.Cells(1, iCols + 1).Value = mrs.Fields(iCols).Name
Next
Worksheets("SavedConfig").Range("A2").CopyFromRecordset mrs
wsConfig.Range("D35") = Now
mrs.Close
cnn1.Close
End Sub
I have edited the code, am getting unspecified error while executing it
How to make the connection string more dynamic instead of hard coding above, and picking up the values from cells of the worksheet of excel.
How to add the code for showing the Last run start time and date and last run end time and date of the query which is being executed, getting tabulated automatically in the excel cells.
Build the connection string by concatenating each parameter.
Sub Conn2SQL()
Const TABLE_NAME = "TableName"
Const DRIVER = "{SQL Server}"
Dim conf
conf = Array("A12", "database", "A13", "server", _
"A14", "password", "A15", "uid")
Dim wb As Workbook, wsConfig As Worksheet, wsOut As Worksheet
Dim i As Integer, strConn As String, sQry As String
Set wb = ThisWorkbook
Set wsConfig = wb.Sheets("Sheet1")
Set wsOut = wb.Sheets("SavedConfig")
' construct connection string
strConn = "driver=" & DRIVER & ";"
For i = 1 To UBound(conf) Step 2
strConn = strConn & conf(i) & "=" & wsConfig.Range(conf(i - 1)).Value & ";"
Next
'Debug.Print strConn
sQry = "SELECT * FROM [" & TABLE_NAME & "]"
' connect to db and run sql
Dim cnn1 As New ADODB.Connection, mrs As New ADODB.Recordset
Dim iCols As Integer
With cnn1
.ConnectionString = strConn
.ConnectionTimeout = 30
.Open
End With
wsConfig.Range("H35") = "LAST RUN STARTED " & Now
cnn1.Execute "USE " & wsConfig.Range(conf(0))
' output
mrs.Open sQry, cnn1
For iCols = 0 To mrs.Fields.Count - 1
wsOut.Cells(1, iCols + 1).Value = mrs.Fields(iCols).Name
Next
wsOut.Cells(2, 1).CopyFromRecordset mrs 'A2
wsConfig.Range("D35") = "LAST RUN COMPLETED " & Now
i = wsOut.Cells(Rows.Count, 1).End(xlUp).Row
MsgBox i & " rows added to " & wsOut.Name, vbInformation
mrs.Close
cnn1.Close
End Sub
Test the connection string with this code
Sub testconnect()
Dim conn As New ADODB.Connection, rs As New ADODB.Recordset, s As String
s = "" ' put connection string here
With conn
.ConnectionString = s
.ConnectionTimeout = 30
.Open
End With
Set rs = conn.Execute("SELECT CURRENT_TIMESTAMP")
MsgBox "Time is " & rs(0), vbOKOnly
conn.Close
End Sub

Resources