Copy Query from Access to Excel - excel

I'm having some problems when I try to import a Query from Access to Excel.
Some days ago I programmed a code (with some help of Google haha) to import a Table from Access to Excel:
Sub importQuery(DBFullName As String, data_sht As Worksheet)
Dim cn As Object, rs As Object
Dim i As Integer
Dim TargetRange As Range
Dim rows As Long, cols As Long
Dim dataEmpty As Boolean
Dim lastColString As String
data_sht.Activate
Application.ScreenUpdating = False
Set TargetRange = data_sht.Range("A1")
Set cn = CreateObject("ADODB.Connection")
cn.Open "Provider=Microsoft.Ace.OLEDB.12.0; Data Source=" & DBFullName & ";" 'the Access file is .accdb
Set rs = CreateObject("ADODB.Recordset")
rs.Open "SELECT * FROM C_Paso2_SM_Cuplas", cn, , , adCmdUnspecified
cols = rs.Fields.Count
rows = data_sht.Range("A" & data_sht.rows.Count).End(xlUp).Row
' Copy titles of the Access Query
For i = 0 To (cols - 1)
TargetRange.Offset(0, i).Value = rs.Fields(i).Name
Next
' Copy data
TargetRange.Offset(1, 0).CopyFromRecordset rs
End Sub
That code works but when I do this:
rs.Open "SELECT * FROM C_Paso2_SM_Cuplas", cn, , , adCmdUnspecified
I'm importing another Query called C_Paso1_SM_Cuplas, from the same file. What can I do? Why am I importing C_Paso1_SM_Cuplas when I say C_Paso2_SM_Cuplas? Is there other possibility to import an Access Query to Excel?

Try this DAO solution.
Sub ImportFromAccessToExcel()
Dim db1 As Database
Dim db2 As Database
Dim recSet As Recordset
Dim strConnect As String
Set db1 = OpenDatabase("C:\Database1.mdb")
strConnect = db1.QueryDefs("Query3").Connect _
& "DSN=myDsn;USERNAME=myID;PWD=myPassword"
Set db2 = OpenDatabase("", False, False, strConnect)
db2.Close
Set db2 = Nothing
Set recSet = db1.OpenRecordset("Query3")
With ActiveSheet.QueryTables.Add(Connection:=recSet, Destination:=Range("$A$4"))
.Name = "Connection"
.RowNumbers = False
.FillAdjacentFormulas = False
.PreserveFormatting = True
.RefreshOnFileOpen = False
.BackgroundQuery = True
.RefreshStyle = xlInsertDeleteCells
.SavePassword = False
.SaveData = True
.AdjustColumnWidth = True
.RefreshPeriod = 0
.PreserveColumnInfo = True
.Refresh BackgroundQuery:=False
End With
recSet.Close
db1.Close
Set recSet = Nothing
Set db1 = Nothing
End Sub

Related

How to use a sql query and get data from one Excel sheet to another in VBA?

I have two excel workbooks. One has a list of target customers and the other has a a table of sales data. I would like to use vba and write a sql query to get the sales history for specific customers and move that sales history to a new ListObject in the Target Customers workbook. What is the best way to do this?
I have tried an OLEDB connection, but I can't seem to get it to work, and I'm even not sure that that is the best way to solve my problem.
This is an example of the code I currently have.
Public Sub GetSales()
Dim targetList As String
'Get list of target customers
Range("A2").Select
Range(Selection, Selection.End(xlDown)).Select
counter = Selection.Rows.Count
targetList = "'" & Range("A2").Value & "'"
For x = 2 To counter
targetList = targetList + ",'" + CStr(Range("A" & CStr(3)).Value) + "'"
Next x
'Query I want to run
'SalesData is the ListObject in the the Sales Data workbook
sqlQuery = "Select * From SalesData WHERE Customer IN " & targetList
With ActiveWorkbook.Connections("SalesData").OLEDBConnection
.BackgroundQuery = True
.CommandText = sqlQuery
.CommandType = xlCmdSql
.Connection = Array(something in here??)
.RefreshOnFileOpen = False
.SavePassword = False
.SourceConnectionFile = ""
.ServerCredentialsMethod = xlCredentialsMethodIntegrated
.AlwaysUseConnectionFile = False
End With
'Return the queried sales data into a list object _
'on a new sheet in the Target Customers workbook
ActiveWorkbook.Worksheets.Add().Name = "Sales History"
Worksheets("Sales History").Activate
With ActiveSheet.ListObjects.Add '(results of query)
.DisplayName = "SalesHistory"
End With
End Sub
Below is a simple connection and query to another workbook.
Sub simple_Query()
Dim cn As ADODB.Connection
Dim rs As ADODB.Recordset
dbpath = "your path here"
Set cn = CreateObject("ADODB.Connection")
Set rs = CreateObject("ADODB.Recordset")
strSQL = "SELECT * FROM [Sheet1$] "
Set vNewWB = Workbooks.Add 'or .CopyFromRecordset rs to open workbook
connstr = "Provider=Microsoft.ACE.OLEDB.12.0;Data source=" & dbpath & ";Extended Properties=""Excel 12.0; HDR=YES; IMEX=1""; Mode=Read;"
cn.Open connstr
Set rs = cn.Execute(CommandText:=strSQL)
vNewWB.Sheets(1).Range("A2").CopyFromRecordset rs
For intcolIndex = 0 To rs.Fields.Count - 1
Range("A1").Offset(O, intcolIndex).Value = rs.Fields(intcolIndex).Name
Next
rs.Close
cn.Close
Set cn = Nothing
Set rs = Nothing
End Sub

VBA Macro read user selected field names from CSV file

I have a sample.csv file with four fields/columns:
Date
City
State
Amount
Below is my code which retrieves all four fields of the data:
Sub LoadFromFile()
Dim fileName As String, folder As String
folder = "d:\Sample.csv"
fileName = ActiveCell.Value
ActiveCell.Offset(1, 0).Range("A1").Select
With ActiveSheet.QueryTables _
.Add(Connection:="TEXT;" & folder & fileName, Destination:=ActiveCell)
.FieldNames = True
.RowNumbers = False
.FillAdjacentFormulas = False
.PreserveFormatting = True
.RefreshOnFileOpen = False
.RefreshStyle = xlInsertDeleteCells
.SavePassword = False
.SaveData = True
.AdjustColumnWidth = True
.RefreshPeriod = 0
.TextFilePromptOnRefresh = False
.TextFilePlatform = 850
.TextFileStartRow = 1
.TextFileParseType = xlDelimited
.TextFileTextQualifier = xlTextQualifierDoubleQuote
.TextFileConsecutiveDelimiter = False
.TextFileTabDelimiter = False
.TextFileSemicolonDelimiter = False
.TextFileCommaDelimiter = True
.TextFileSpaceDelimiter = False
.TextFileColumnDataTypes = Array(1, 1, 1, 1)
.TextFileTrailingMinusNumbers = True
.Refresh BackgroundQuery:=False
End With
End Sub
My requirement is to display only three fields/columns: Date, City and Amount. How can I do that?
Sub CSVData()
Dim con As ADODB.Connection
Dim rs As ADODB.Recordset
Set con = New ADODB.Connection
Set rs = New ADODB.Recordset
Dim currentDataFilePath As String
Dim currentDataFileName As String
Dim nextRow As Integer
Dim emptystr As String
'"H:\projectfiles\csv\", "Book.csv"
currentDataFilePath = ("H:\projectfiles\csv\")
currentDataFileName = ("Book.csv")
emptystr = "NULL"
con.Provider = "Microsoft.Ace.OLEDB.12.0"
con.ConnectionString = "Data Source=" & currentDataFilePath & ";" & "Extended Properties=""text;HDR=Yes;FMT=Delimited;"""
'MsgBox currentDataFilePath
con.Open
rs.Open "SELECT * FROM [" & currentDataFileName & "] ", con
rs.MoveFirst
'nextRow = Worksheets("Sheet3").UsedRange.Rows.Count + 1
'Worksheets("Sheet3").Cells(nextRow, 1).CopyFromRecordset rs
'MsgBox rs.RecordCount
With rs
Do Until .EOF
'check the field is not null before process
If Not IsNull(rs(0)) Then
custordernum = rs(0)
End If
If Not IsNull(rs(1)) Then
ContactNAme = "" & Replace(rs(1), "'", " ")
Else
ContactNAme = emptystr
End If
If Not IsNull(rs(2)) Then
colladd1 = "" & Replace(rs(2), "'", " ")
Else
colladd1 = emptystr
End If
MsgBox colladd1
.MoveNext
Loop
End With
rs.Close
con.Close
End Sub
This is your alternative doing exactly what you want so you can copy and change to your specification
Sub CSVDataBok()
Dim con As ADODB.Connection
Dim rs As ADODB.Recordset
Set con = New ADODB.Connection
Set rs = New ADODB.Recordset
Dim currentDataFilePath As String
Dim currentDataFileName As String
Dim nextRow As Integer
Dim emptystr As String
'"H:\projectfiles\csv\", "Book.csv"
currentDataFilePath = ("H:\resources\")
currentDataFileName = ("Book2.csv")
emptystr = "NULL"
con.Provider = "Microsoft.Ace.OLEDB.12.0"
con.ConnectionString = "Data Source=" & currentDataFilePath & ";" & "Extended Properties=""text;HDR=Yes;FMT=Delimited;"""
'MsgBox currentDataFilePath
con.Open
rs.Open "SELECT Date,City,State,Amount FROM [" & currentDataFileName & "] ", con
rs.MoveFirst
nextRow = Worksheets("Sheet3").UsedRange.Rows.Count + 1
Worksheets("Sheet3").Cells(nextRow, 1).CopyFromRecordset rs
rs.Close
con.Close
End Sub

VBA error when chinese characters are present in database table

I have an excel application which connects to HANA database using ODBC and fetch table data in next sheet on button click. I am using below code to fetch data from database:-
Function importRoutine(sheet As String, provider As String, databaseschema As String, server As String, app As String, row As Long, column As Long, commandText As String, displayname As String, errorFlag As Boolean) As Integer
Debug.Print commandText
Dim l As QueryTable
Dim rs As Object
Dim cnt As ADODB.Connection
Dim cmd As ADODB.Command
Dim iCols As Integer
Set cnt = New ADODB.Connection
Set cmd = New ADODB.Command
Set rcd = New ADODB.Recordset
Dim rangesheet As String
rangesheet = Sheets(sheet).Cells(row + 1, column).Address
Dim connectionsheet As String
connectionsheet = "Driver=" + provider + ";SERVERNODE=" + server + ";" + getAuthentication + "; CS=" + databaseschema + ""
cnt.ConnectionString = connectionsheet
cnt.Open
Set cmd.ActiveConnection = cnt
cmd.commandText = commandText
cmd.CommandType = adCmdText
rcd.Open commandText, cnt '', adOpenStatic
Set rs = CreateObject("ADODB.RECORDSET")
rs.ActiveConnection = cnt
rs.Open commandText, cnt
With Sheets(sheet).ListObjects.Add(SourceType:=3, Source:=rs, Destination:=Range(Sheets(sheet).Cells(row, column).Address)).QueryTable
'.commandText = commandText
'.CommandType = xlCmdSql
.RowNumbers = False
.FillAdjacentFormulas = False
.PreserveFormatting = True
.RefreshOnFileOpen = False
.BackgroundQuery = True
.RefreshStyle = xlInsertDeleteCell
.SavePassword = False
.SaveData = True
.AdjustColumnWidth = False
.RefreshPeriod = 0
.ListObject.Name = displayname
.PreserveColumnInfo = False
On Error Resume Next
.Refresh BackgroundQuery:=False
End With
Sheets(sheet).ListObjects(displayname).TableStyle = "TableStyleMedium10"
importRoutine = 0
Call deleteConnection
CloseRecordset:
rs.Close
Set rs = Nothing
CloseConnection:
cnt.Close
Set cnt = Nothing
On Error GoTo 0
End Function
The code works fine if table contains english characters. But if the table has some special characters like some chinese characters, it is not able to put the data in next sheet and throwing error.
Is there any restriction on VBA not able to fetch/view data containing chinese characters?
I was able to resolve that error. The issue was in data type of column in my table. It was varchar which was creating unicode error. When i changed the same to NVARCHAR, data fetch from database worked fine on the sheet for all the other language characters.

How to refresh table data on all sheets

I need to run a VBScript that can dynamically set a SQL Server connection string, taking server name and database name from Excel cells, and refresh tables in all worksheets of the file.
I currently have this script against a 'Refresh' button on the 'Setup' sheet (from where it takes the server and database names):
Sub Refresh_Click()
Dim Sh As Worksheet
Dim sServer As String
Dim sDatabase As String
Dim sTableName As String
Dim vDestinationRg As Variant
Dim sQuery(1 To 24) As String
Dim vQueryArray As Variant
Dim i As Integer
Dim j As Integer
Dim isSplit As Boolean
Dim sUsername As String
Dim sPassword As String
Set Sh = ActiveSheet
j = 1
isSplit = True
vQueryArray = Application.Transpose(Sh.Range("U1:U10"))
For i = LBound(vQueryArray) To UBound(vQueryArray)
If vQueryArray(i) <> "" Then
isSplit = False
sQuery(j) = sQuery(j) & Trim(vQueryArray(i)) & vbCrLf
ElseIf Not isSplit Then
isSplit = True
j = j + 1
End If
Next i
sServer = Sheets("Setup").Range("F5").Value
sDatabase = Sheets("Setup").Range("F7").Value
vDestinationRg = Array("$H$12")
sUsername = "username"
sPassword = "********"
For i = LBound(sQuery) To UBound(sQuery)
If sQuery(i) = "" Then Exit Sub
sTableName = "Result_Table_" & Replace(Replace(Sh.Name, " ", ""), "-", "") & "_" & i
On Error Resume Next
Sh.ListObjects(sTableName).Delete
On Error GoTo 0
With Sh.ListObjects.Add(SourceType:=0, Source:=Array( _
"OLEDB;Provider=SQLOLEDB.1;User Id=" & sUsername & "; Password=" & sPassword & ";Data Source=" & sServer & ";Initial Catalog=" & sDatabase & ""), Destination:=Sh.Range(vDestinationRg(i - 1))).QueryTable
.CommandText = sQuery(i)
.RowNumbers = False
.FillAdjacentFormulas = False
.PreserveFormatting = True
.RefreshOnFileOpen = False
.BackgroundQuery = True
.RefreshStyle = xlInsertDeleteCells
.SavePassword = False
.SaveData = True
.AdjustColumnWidth = True
.RefreshPeriod = 0
.PreserveColumnInfo = True
.ListObject.DisplayName = sTableName
.Refresh BackgroundQuery:=False
End With
Next
End Sub
I have a select query written in cell "U1" of the 'Setup' sheet and it creates and populates the table into the destination range starting from "H12".
But instead of placing the query on the 'Setup' sheet I want to write queries on different worksheets which would populate tables in the respective worksheets, with only this one Refresh button click on the Setup sheet.
How can I do this?
I have been told it can be achieved without writing VBScript also, but no luck there! I tried adding SQL server connections to the workbook, but can't make it dynamic from there.

Bulk Import from CSV to SQL Server using Excel VBA ADODB

I am trying to import a large number of data from a CSV file to a SQL Sever database table. I am able to write line by line but that takes too long. What I have below fails on "FROM [C:\Temp\tblOPTExportData.csv]" during oComm.Execute. Any help would be appreciated.
On Error GoTo err_me
Dim locComm As New ADODB.Command
Dim locConnection As New ADODB.Connection
Dim locRst As New ADODB.Recordset
Dim ee As Boolean
Dim su As Boolean
Dim strSQLQuery As String
Dim shtDash As Worksheet
Dim shtData As Worksheet
Dim shtOP As Worksheet
With Application
ee = .EnableEvents
su = .ScreenUpdating
If ee Then .EnableEvents = False
If Not su Then .ScreenUpdating = True
End With
With ThisWorkbook
Set shtDash = .Sheets("Dashboard")
Set shtData = .Sheets("Data")
Set shtOP = .Sheets("OP")
End With
With locConnection
.CommandTimeout = 0
.ConnectionString = "Provider=SQLOLEDB;Server=sql-ewhcld-1000; Database=xxxxxxxxxxxxxx; User ID=tenant-xxxxxxxxxxxxxxx; Password=yeahidontthinkso; Trusted_Connection=True; Pooling=True; MultipleActiveResultSets=False"
.Open
End With
' ____________________________
' / \
' | IMS Factory Model Data |
' \____________________________/
'
'With statRng
' .Value = "Factory Model Phase Data // Importing"
' .Font.Color = 8421504
' .Characters(Start:=29, Length:=9).Font.Color = 10192433 'Blue
'End With
With shtOP
endRow = .Cells(.Rows.count, 2).End(xlUp).Row 'B (2)
End With
If endRow < 3 Then Err.Raise Number:=vbObjectError + 20002, Source:="exportData_Excel", Description:="No data found: 'OP' sheet, column 2 (B)."
If Not rangetoCSV("B3:K" & endRow, "tblOPTExportData", 201, , , "OP") Then Err.Raise Number:=vbObjectError + 30001, Description:="rangetoCSV, 'tblGates'"
strSQLQuery = "INSERT INTO optData (opsType, opsUID, opsDesc, opsProgram, opsFlight, opsProductAreaL1, opsAssignee, opsGenDate, opsECD, opsStatus) " & _
"SELECT Type, UID, Description, Program, Flight, L-1 IPT, Assignee, Generated, ECD, Status FROM [C:\Temp\tblOPTExportData.csv]"
With oComm
.ActiveConnection = locConnection
.CommandText = strSQLQuery
.Execute
End With
You need to use BULK INSERT rather than INSERT INTO. Try something like this:
strSQLQuery = "BULK INSERT optData " & _
"FROM C:\Temp\tblOPTExportData.csv " & _
"WITH (FIRSTROW = 2, FIELDTERMINATOR = ',', " & _
"ROWTERMINATOR = '\n', TABLOCK)"
With oComm
.ActiveConnection = locConnection
.CommandType = adCmdText
.CommandText = strSQLQuery
.Execute
End With

Resources