the macro below exports data to SQL tables, when the name of the table has no space, it works perfectly, but if the name has a space, it blocks,
it blocks on the rs.Open line tableName, Cn, adOpenKeyset, adLockOptimistic
I tried the hooks [...] the apostrophe '...' and ... but nothing works
`
Sub Injection()
Dim Cn As ADODB.connection
Dim ServerName As String
Dim DatabaseName As String
Dim tableName As String
Dim UserID As String
Dim Password As String
Dim rs As ADODB.recordset
ServerName = "vmalsdisdb"
DatabaseName = "Produits"
tableName = "PRELEVEMENT PRODUIT"
UserID = ""
Password = ""
Set rs = New ADODB.recordset
Set Cn = New ADODB.connection
Cn.Open "Driver={SQL Server};Server=" & ServerName & ";Database=" & DatabaseName & _
";Uid=" & UserID & ";Pwd=" & Password & ";"
rs.Open tableName, Cn, adOpenKeyset, adLockOptimistic`
That's weird! It works fine for me in my test scenario!
Sub ADOExcelSQLServer()
'
' FOR THIS CODE TO WORK
' In VBE you need to go Tools References and check Microsoft Active X Data Objects 2.x library
'
Dim Cn As ADODB.Connection
Dim Server_Name As String
Dim Database_Name As String
Dim User_ID As String
Dim Password As String
Dim SQLStr As String
Dim rs As ADODB.Recordset
Set rs = New ADODB.Recordset
Server_Name = "EXCEL-PC\SQLEXPRESS" ' Enter your server name here
Database_Name = "Test Method" ' Enter your database name here
User_ID = "" ' enter your user ID here
Password = "" ' Enter your password here
SQLStr = "SELECT * FROM [mytable]" ' Enter your SQL here
Set Cn = New ADODB.Connection
Cn.Open "Driver={SQL Server};Server=" & Server_Name & ";Database=" & Database_Name & _
";Uid=" & User_ID & ";Pwd=" & Password & ";"
rs.Open SQLStr, Cn, adOpenStatic
' Dump to spreadsheet
For iCols = 0 To rs.Fields.Count - 1
Worksheets("Sheet1").Cells(1, iCols + 1).Value = rs.Fields(iCols).Name
Next
With Worksheets("sheet1").Range("a2:z500") ' Enter your sheet name and range here
'.ClearContents
.CopyFromRecordset rs
End With
' Tidy up
rs.Close
Set rs = Nothing
Cn.Close
Set Cn = Nothing
End Sub
I suppose you can try triple quotes around any 'weird' naming conventions, like spaces in names, or special characters in names.
thank you all for your answers, the problem was not worry in space but in one of the Tables, I was able to bypass the problem by replacing the cursor type "adOpenKeyset" by "adOpenDynamic"
but his understanding the problem, may be that another user worked on the table ?!
Related
I've a below VBA code and I want to read four values a, b, c, d from an excel column (A1:A4) so those can be part of my SQL query IN statement when I connect to database.
I build up the sWHEREclause to create ('a','b','c','d') string that but the final SQL query SQLStr seems to have some error and my code fails.
Can someone please help.
Thank you so much in advance.
Sub ADOExcelSQLServer()
Dim Cn As ADODB.Connection 'connection variable
Dim Server_Name As String ' text type
Dim Database_Name As String
Dim User_ID As String
Dim Password As String
Dim SQLStr As String
Dim rs As ADODB.Recordset ' Database connection variable
Dim rRange As Range
Dim rCell As Range
Dim sWHEREclause As String
Set rs = New ADODB.Recordset
Server_Name = "server name"
Database_Name = "Database name"
Set rRange = Sheet1.Range("A1:A4")
For Each rCell In rRange
sWHEREclause = sWHEREclause & "'" & rCell & "',"
Next rCell
'SQLStr = "Select * from MASTER_QUERY mq where mq.ModelNum in ('a','b','c','d')" 'commented line
SQLStr = "Select * from MASTER_QUERY mq where mq.ModelNum IN (" & sWHEREclause & ")"
Set Cn = New ADODB.Connection 'set connection with databse
Cn.Open "Provider=SQLOLEDB;Data Source=" & Server_Name & "; Initial Catalog=" & Database_Name & "; Integrated Security=SSPI;" 'connection parameter to the database
rs.Open SQLStr, Cn, adOpenStatic
' Dump to spreadsheet
With Worksheets("sheet1").Range("b2:z500") ' Enter your sheet name and range here
' Range(A1).Value = "ID)"
.ClearContents ' clear content first in excel
.CopyFromRecordset rs
End With
' Tidy up
rs.Close
Set rs = Nothing
Cn.Close
Set Cn = Nothing
End Sub
Your string ends with a ,
do your loop like this:
Dim delim as string
delim = ""
For Each rCell In rRange
sWHEREclause = sWHEREclause & delim & "'" & rCell & "'"
delim = ", "
Next rCell
I want to import data from 2 columns in SQL server, im following this code from http://buffalobi.com/excel/excel-vba-import-sql-server-data/, whats wrong?
Private Sub CommandButton2_Click()
Call CommandButton1_Click
Dim conn As New ADODB.Connection, cmd As New ADODB.Command, rs As New ADODB.Recordset
With conn
.ConnectionString = _
"Provider = Microsoft.ACE.OLEDB.12.0; " & _
"data source=localhost; " & _
"initial catalog=PTrails_Core_DB;" & _
"integrated security=True;"
.Open
End With
and i get this message
I would set 'ConnectionString' as variable and use that to open. If this doesn't work, it would have to be the actual link you're referring to that's causing an issue. Maybe because it's ending on semicolon.
Dim ConnectionString as String
ConnectionString = "Provider = Microsoft.ACE.OLEDB.12.0;data source=localhost;initial catalog=PTrails_Core_DB;integrated security=True"
conn.Open ConnectionString
This will do what you want.
Sub ImportFromSQLServer()
Dim Cn As ADODB.Connection
Dim Server_Name As String
Dim Database_Name As String
Dim User_ID As String
Dim Password As String
Dim SQLStr As String
Dim RS As ADODB.Recordset
Set RS = New ADODB.Recordset
Server_Name = "your_server_name"
Database_Name = "Northwind"
'User_ID = "******"
'Password = "****"
SQLStr = "select Field1, Field2 from dbo.TBL" 'and PostingDate = '2006-06-08'"
Set Cn = New ADODB.Connection
Cn.Open "Driver={SQL Server};Server=" & Server_Name & ";Database=" & Database_Name & ";"
'& ";Uid=" & User_ID & ";Pwd=" & Password & ";"
RS.Open SQLStr, Cn, adOpenStatic
With Worksheets("Sheet1").Range("A1")
.ClearContents
.CopyFromRecordset RS
End With
RS.Close
Set RS = Nothing
Cn.Close
Set Cn = Nothing
End Sub
using vba macro I used the below query and I can able to get the results
strsQL = "SELECT name,address, balance1,balance2,balance3 FROM userInfo.csv"
if there any possibility to get the sql results using column index , instead of using column name (address) in VBA macro
Try it this way.
Sub GetMyCSVData()
Dim xlcon As ADODB.Connection
Dim xlrs As ADODB.Recordset
Set xlcon = New ADODB.Connection
Set xlrs = New ADODB.Recordset
Dim currentDataFilePath As String
Dim currentDataFileName As String
Dim nextRow As Integer
currentDataFilePath = "C:\My Data Folder\"
currentDataFileName = "My Data File"
xlcon.Provider = "Microsoft.Jet.OLEDB.4.0"
xlcon.ConnectionString = "Data Source=" & currentDataFilePath & ";" & "Extended Properties=""text;HDR=Yes;FMT=Delimited;"""
xlcon.Open
xlrs.Open "SELECT FirstName, Surname, Age FROM [" & currentDataFileName & ".csv] WHERE SomeNumber > 10", xlcon
xlrs.MoveFirst
nextRow = Worksheets("Sheet1").UsedRange.Rows.Count + 1
Worksheets("Sheet1").Cells(nextRow, 1).CopyFromRecordset xlrs
xlrs.Close
xlcon.Close
Set xlrs = Nothing
Set xlcon = Nothing
End Sub
I am trying to connection sqlserver from VBA program, I refer to the following code to achieve it, but I
got the problem: connection failed. Any help. Thank you in advance.
Code:
Sub ADOExcelSQLServer()
' Carl SQL Server Connection
'
' FOR THIS CODE TO WORK
' In VBE you need to go Tools References and check Microsoft Active X
'Data Objects 2.x library
Dim Cn As ADODB.Connection
Dim Server_Name As String
Dim Database_Name As String
Dim User_ID As String
Dim Password As String
Dim SQLStr As String
Dim rs As ADODB.Recordset
Set rs = New ADODB.Recordset
Server_Name = "EXCEL-PC\EXCELDEVELOPER" ' Enter your server name here
Database_Name = "AdventureWorksLT2012" ' Enter your database name here
User_ID = "" ' enter your user ID here
Password = "" ' Enter your password here
SQLStr = "SELECT * FROM [SalesLT].[Customer]" ' Enter your SQL here
Set Cn = New ADODB.Connection
Cn.Open "Driver={SQL Server};Server=" & Server_Name & ";Database=" & Database_Name & _
";Uid=" & User_ID & ";Pwd=" & Password & ";"
rs.Open SQLStr, Cn, adOpenStatic
' Dump to spreadsheet
With Worksheets("sheet1").Range("a1:z500") ' Enter your sheet name and range here
.ClearContents
.CopyFromRecordset rs
End With
' Tidy up
rs.Close
Set rs = Nothing
Cn.Close
Set Cn = Nothing
End Sub
test this.
Sub cn()
Dim con As New ADODB.Connection
Dim cmd As New ADODB.Command
Dim rst As New ADODB.Recordset
Dim i As Integer
con.ConnectionString = "Provider=SQLOLEDB.1;" _
& "Server=(local);" _
& "Database=AdventureWorksLT2012;" _
& "Integrated Security=SSPI;" _
& "DataTypeCompatibility=80;"
con.Open
Set cmd.ActiveConnection = con
cmd.CommandText = "SELECT * FROM [SalesLT].[Customer]"
Set rst = cmd.Execute
Range("A1").CopyFromRecordset rst
con.Close
Set con = Nothing
End Sub
I checked your code and it works for me. So I think it should be a SQL configuration problem e.g. permissions or port issue. You need to test connection status by using sqlserver client and check related connection problem.
How to execute a query in MS Access db from Excel VBA code or macro.
MS-Access query accepts some parameters, that needs to be passed from Excel.
Thanks
Here is one possibility:
Dim cn As Object
Dim strFile As String
Dim strCon As String
Dim strSQL As String
strFile = "C:\docs\Test.mdb"
strCon = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" & strFile
''Late binding, so no reference is needed
Set cn = CreateObject("ADODB.Connection")
cn.Open strCon
strSQL = "INSERT INTO ATable (AField) " _
& "VALUES (" & Sheet1.[A1] & ")"
cn.Execute strSQL
cn.Close
Set cn = Nothing
You can also refer in-line in the sql to a dataset from Excel.
EDIT re comments
Using a command:
strSQL = "SELECT * FROM ATable " _
& "WHERE AField = #AField"
With cmd
Set .ActiveConnection = cn
.CommandText = strSQL
.CommandType = 1 'adCmdText
''ADO Datatypes are often very particular
''adSmallInt = 2 ; adParamInput = 1
.Parameters.Append .CreateParameter("#AField", 2, 1, , Sheet1.[A1])
End With
Set rs = cmd.Execute
See also: http://support.microsoft.com/kb/181782
This uses ADODB.
Set m_Connection = New Connection
If Application.Version = "12.0" Then
m_Connection.Provider = "Microsoft.ACE.OLEDB.12.0"
Else
m_Connection.Provider = "Microsoft.Jet.OLEDB.4.0"
End If
m_Connection.Open <full path to Access DB>
If m_Connection.State > 0 Then
Dim rsSource As New Recordset
rsSource.Open strQuery, m_Connection, adOpenForwardOnly, adLockReadOnly
Dim result As Long
Dim rngTarget As Range
rngTarget = ThisWorkbook.Worksheets(m_SheetName).Range("A1")
If Not rsSource.BOF Then
result = rngTarget.CopyFromRecordset(rsSource)
End If
If rsSource.State Then rsSource.Close
Set rsSource = Nothing
End If
So it runs the query and puts it where you like. strQuery is the name of a query in the db or an SQL string.