Query SQL Table And Store Results In Array - sql-server

I am wanting to query a SQL Server Table and store the results from that query in an array. I am only returning a Distinct() from one field so it should be pretty straight forward. My syntax produces the error
Invalid Qualifier
On this line of code Set r = conn.Execute and it highlights the word conn How should I re-write this syntax to still use ADO but be able to successfully run this procedure?
Public Function ReturnData()
Dim c As ADODB.Connection
Dim r As ADODB.Recordset
Dim f As ADODB.Field
Dim conn As String
Dim arrResults() As Variant
Set c = New ADODB.Connection
With c
.Provider = "sqloledb.1"
With .Properties
.Item("Data Source") = "ServerName"
.Item("Initial Catalog") = "Database"
.Item("PassWord") = "password"
.Item("User ID") = "user"
End With
.Open
Set r = conn.Execute("SELECT Distinct(Name) from registered where cancelled IS NULL;")
i = 0
r.MoveFirst
Do Until rst.EOF
arrResults(i) = rst.Fields(0)
i = i + 1
Loop
rst.Close
Set rst = Nothing
c.Close
End Function

Another way to get a recordset into an array is to use Split and Recordset.GetString. It avoids the loop anyway. Here's an example.
Public Sub RsToArray()
Dim adoCon As ADODB.Connection
Dim adoRs As ADODB.Recordset
Dim vaLocations As Variant
Set adoCon = New ADODB.Connection
adoCon.Open sConn
Set adoRs = adoCon.Execute("SELECT DISTINCT LocationName FROM Locations")
vaLocations = Split(adoRs.GetString, vbCr)
Debug.Print Join(vaLocations, "|")
adoRs.Close
adoCon.Close
Set adoRs = Nothing
Set adoCon = Nothing
End Sub

you've got conn is a string there, c is a connection - can you do c.execute
try
Set r = c.Execute(...
I'm not sure if you need a command object, if you do, then see
https://msdn.microsoft.com/en-us/library/ms675065%28v=vs.85%29.aspx
to see how to make a command for your connection and execute it
Anyhow, at the moment you are trying to 'execute' on a string - string is a primitive type and does not execute on the DB - I think you just mixed c and conn up - let us know how it goes

Related

Attempting to connect to SQL Server to query data using VBA but running into constant problems. Issues with code?

Here is the VBA code I have in the module:
Private Sub Workbook_Open()
Dim adoDBConn As New ADODB.connection
Dim adoDbRs As New ADODB.Recordset
Dim selectCmd As New ADODB.Command
adoDBConn.Open "Provider=SQLOLEDB;Data Source=LAPTOP-N0CT1GQ5;Initial Catalog=Interest_Analysis;User Id = ***;Password = ***;"
selectCmd.ActiveConnection = adoDBConn
selectCmd.CommandText = "County, cntyvtd, Name, Votes FROM 2020_General_Election_Returns_import_to_SQL"
Set adoDbRs = selectCmd.Execute(, , adCmdText)
Dim cellRange As Range
Set cellRange = Range(Cells(2, 2), Cells(Row.Count, 1)).EntireRow
cellRange.ClearContents
'The Worksheet tab is called "Data"
Dim ws As Worksheet
Set ws = ThisWorkbook.Worksheets("Data")
ws.Activate
If adoDbRs.EOF = False Then ws.Cells(2, 2).CopyFromRecordset adoDbRs
ws.Cells(1, 2) = "County"
ws.Cells(1, 3) = "cntyvtd"
ws.Cells(1, 4) = "Name"
ws.Cells(1, 5) = "Votes"
adoDbRs.Close
Set adoDbRs = Nothing
Set selectCmd = Nothing
adoDBConn.Close
Set adoDBConn = Nothing
End Sub
What I'm doing is using an ADODB connection to connect to SQL Server in Microsoft Excel and using VBA code to interact with the server so that the data can populate in an Excel sheet. I got much of the code template from a website, but have been running into a lot of errors and the debugger keeps pointing at different lines. Right now, it's pointing at the Set adoDbRs = selectCmd.Execute() line and saying Incorrect syntax near ',' and it would also go to the If adoDbRs.EOF = False and say Object not found. I might be missing a foundational statement or something I need to start with, so let me know what the issue is. Thank you!
To debug VBA and figure out how to pull SQL server data into an Excel spreadsheet.
This worked fine for me (against Oracle, but SQL server should work the same way)
Private Sub SOTest()
Dim adoDBConn As New adodb.Connection
Dim adoDbRs As adodb.Recordset 'no `New` here
Dim selectCmd As New adodb.Command
Dim ws As Worksheet, f As adodb.Field
Set ws = ThisWorkbook.Worksheets("Data")
adoDBConn.Open "connection string here"
selectCmd.ActiveConnection = adoDBConn
selectCmd.CommandText = "select * from myTable"
Set adoDbRs = selectCmd.Execute(, , adCmdText)
'clear the output range
ws.Range(ws.Cells(1, 2), ws.Cells(ws.Rows.Count, 15)).ClearContents
ResultsToSheet adoDbRs, ws.Cells(1, 2)
ws.Activate
adoDbRs.Close
adoDBConn.Close
End Sub
'Place a recordset contents on a worksheet (incl. headers)
' starting at `rng`
Sub ResultsToSheet(rs As adodb.Recordset, rng As Range)
Dim c As Range, f As adodb.Field
Set c = rng.Cells(1) ' top left
For Each f In rs.Fields
c.Value = f.Name 'write the field header
Set c = c.Offset(0, 1) 'next header cell
Next f
If Not rs.EOF Then
'write the data starting on the next row
rng.Cells(1).Offset(1).CopyFromRecordset rs
End If
End Sub

Object variable or With block variable not set.

I'm trying to connect SQL Server to Access. I have the connection function in a module. I call this function in another module.
Here is the code in my module:
'Variabel voor SQL Server Connectie
Public SQLConnectie As ADODB.Connection
'Connecten met SQL Server
Public Function DBConn() As ADODB.Connection
If Not (SQLConnectie Is Nothing) Then
Set SQLConnectie = New ADODB.Connection
With SQLConnectie
.CommandTimeout = 15
.Mode = adModeReadWrite
.ConnectionString = "Provider=SQLNCLI11;Server=dafehvmvdsql3;Database=PROVOMotorenfabriek;Integrated Security=SSPI; Persist Security Info=False"
.Open
End With
End If
Set DBConn = SQLConnectie
Set SQLConnectie = Nothing
End Function
And below the code in the module which executes the stored procedure in SQL Server:
Call DBConn.Execute("EXEC spStoringToevoegen " & productielijnMW & ", " & Forms(Formnaam)!cbLijngedeelte & ".............etc
I get the error: Object variable or With block variable not set. Every answer I find says I need to put set in front of some variables but I can't find which one this should be.
Thanks in advance,
Adding this to sample parameters.
As I said my VBA is very rusty (and I find VBA particularly weird language to work with, add Access to that it sounds like a misery to me). It would be much easier if you used some other backend (and language as well). Anyway, here is a sample with parameters in VBA (Excel):
Sub Macro1()
Dim oRecordset1 As ADODB.Recordset
Dim oConnection As ADODB.Connection
Dim oCommand As ADODB.Command
Dim oParameter1 As ADODB.Parameter
Dim oParameter2 As ADODB.Parameter
Set oConnection = New ADODB.Connection
Set oCommand = New ADODB.Command
oConnection.ConnectionString = "Provider=SQLNCLI11.0;Data Source=.\SQLExpress;Trusted_connection=Yes"
oConnection.Open
oCommand.ActiveConnection = oConnection
oCommand.CommandType = 4
oCommand.CommandText = "Northwind.dbo.[CustomersSelectLike]"
Set oParameter1 = oCommand.CreateParameter("#country", 130, 1, -1) ' adWChar
oCommand.Parameters.Append oParameter1
oCommand.Parameters("#country").Value = "USA"
Set oParameter2 = oCommand.CreateParameter("#customer", 130, 1, -1)
oCommand.Parameters.Append oParameter2
oCommand.Parameters("#customer").Value = "%"
Set oRecordset = oCommand.Execute()
Sheet1.Range("A1").CopyFromRecordset (oRecordset)
End Sub

Error: "Command text was not set for the command object" when running a Stored Procedure from SQL on VBA

I'm trying to run a stored procedure on VBA using the following VBA code:
Please can someone advise: I get the error at "rs.Open".
Sub connection()
Dim Conn As ADODB.connection
Dim ADODBCmd As ADODB.Command
Dim rs As ADODB.Recordset
Dim i As Integer
Dim constring As String
Dim location As String 'the server
Dim password As String
location = "10.103.98.18"
password = "password"
constring = "Provider=SQLOLEDB; Network Library=DBMSSOCN;Data Source=" & location & ";Command Timeout=0;Connection Timeout=0;Packet Size=4096; Initial Catalog=ElColibri; User ID=Analyst1; Password=password;"
Set Conn = New ADODB.connection
Conn.connectionString = constring
'On Error GoTo ConnectionError
Conn.Open
'loginstatus = False
'Exit Sub
'errorhandl0
'ConnectionError:
'MsgBox "Not possible to log in. Have you entered the correct password?"
'open recordset
Set ADODBCmd = New ADODB.Command
ADODBCmd.ActiveConnection = Conn
ADODBCmd.CommandTimeout = 1200
ADODBCmd.CommandText = ["ukrmc.dbo.FridayCommentary"]
ADODBCmd.CommandType = 4 'adCmdStoredProc
ADODBCmd.Execute
Set rs = New ADODB.Recordset
rs.ActiveConnection = Conn
rs.Open
Conn.Close
Set Conn = Nothing
Set ADODBCmd = Nothing
'Paste to spreadsheet
ThisWorkbook.Worksheets("macrotest").Range("a2").CopyFromRecordset
'Set rs = conn.Execute(Query)
rs.Close
Set rs = Nothing
End Sub
To me the code makes logical sense to me so I am not sure what the error means. Because to me, I have set text for the command object.
You are not connecting the recordset to your command. Assuming that your stored procedure issues a SELECT, change your code to
Set rs = ADODBCmd.Execute
thisWorkbook.Worksheets("macrotest").Range("a2").CopyFromRecordset rs
The Execute-Method will return a Recordset as result, no need to create one by yourself.
Or you should add the command object to the open operation
rs.Open ADODBCmd

"Application Defined or Object Defined" error in VBA-SQL connection

I am trying to write an Exce-Vba code for SQL connection. The code, first will open the connection to the server, then it will copy a 4 columns of table (Range("C22:G81")) from my Excel-sheet to the SQL-server (I am only trying to send numerical table now as a test, I don't send any column name)
I have been trying to solve a "Application Defined or Object Defined" error quite long time. I get the error for the connection string strCon = "Provider=Microsoft.ACE.OLEDB.12.0; Data Source=" & strName & ";Extended Properties=""Excel 12.0;"
I even tried with another version with password option like strCon = "Provider=Microsoft.ACE.OLEDB.12.0; Data Source=" & strName & ";Extended Properties=""Excel 12.0; Jet OLEDB:Database Password='passwd';"
But I get the same error. I am quite new in SQL-coding. I wonder if I am missing something important.
Lasly, I don't know if it is related to this error, but I manually created 4 columns in the SQL server for my 4 columns in the Excel. Do I need to write something specific that those 4 columns in the Excel-sheet will find the right columns in the SQL-server?
Thanks in advance...
The code:
Private Sub inlasning()
Dim MyWorkBook As Workbook
Dim rs As New ADODB.Recordset
Dim conn As New ADODB.Connection
Dim ServerName As String, DataBaseName As String, strSQL As String
Set conn = New ADODB.Connection
ServerName = "E45c7642"
DataBaseName = "Tables"
' Specify the OLE DB provider
conn.Provider = "sqloledb"
' Set SQLOLEDB connection properties
conn.Properties("Data Source").Value = ServerName
conn.Properties("Initial Catalog").Value = DataBaseName
' Windows NT authentication.
conn.Properties("Integrated Security").Value = "SSPI"
conn.Open
Dim ValidSheet As Worksheet
Dim HeaderRange As Range
Dim DataRange As Range
Dim ColRange As Range
Dim LastRange As Range
Dim strName As String, strCon As String
strName = ThisWorkbook.FullName
Application.ScreenUpdating = False
Set ValidSheet = ThisWorkbook.Sheets("Sheet2") '
Set HeaderRange = ValidSheet.Range("C20:G21")
Set ColRange = HeaderRange.Find(TheHeader, , , xlWhole)
Set LastRange = ColRange.End(xlDown)
Set DataRange = ValidSheet.Range("C22:G81") ' This is what I am trying to transfer, only numeric values without column names
strCon = "Provider=Microsoft.ACE.OLEDB.12.0; Data Source=" & strName _
& ";Extended Properties=""Excel 12.0;"
conn.Open strCon
strSQL = "SELECT * FROM [" & ValidSheet.Name & "$" & Replace(DataRange, "$", "") & "];"
rs.Open strSQL, dbclass, adOpenStatic, adLockReadOnly
arrData = rs.GetRows
rs.Close
conn.Close
Set rs = Nothing
Set conn= Nothing
Set ValidSheet = Nothing
End Sub
After getting the same error for the "connection string", I changed the strategy, and I used dbclass procedure to open a connection. So the new code is like below. (I found this coding from a guy, but he is on vacation now, so I can't ask him).
It gets connection (dbclass) properties automatically, which are saved in the main ThisWorkbook. This code doesn't give any error at all, but it doesn't copy the column from the Excel to the database. I tried different versions for the sql-query, like SQL = .... VALUES('result') or SQL = .... VALUES(result), but there is no result again, without error.
Private Sub Testing_Click()
Dim FindColValues() As Double
Dim ValidBook As Workbook
Dim ValidSheet As Worksheet
Dim DataRange As Range
Dim dataa As Range
Application.ScreenUpdating = False
TheSheet = "Sheet2"
Set ValidSheet = Worksheets(TheSheet)
Set DataRange = ValidSheet.Range("C21:C81")
' Below creating an array "result(it)" from the seleced range.
For Each dataa In DataRange
ReDim Preserve result(it)
result(it) = dataa.Value
it = it + 1
Next
' Below is just an alternative array for "in case"
arrData = ValidSheet.Range("C22:G81").Value
SQL = "INSERT INTO Table_test (Column1) VALUES ('result()');"
dbclass.ExecuteSQL SQL
End Sub
Below is dbclass connection properties which is read automatically by the other function:
Private Sub Workbook_Open()
Dim connOk As Boolean
Dim rs As New ADODB.Recordset
Dim MyWorkBook As Workbook
Dim CurSheet As Worksheet
Set dbclass = New clsDB
dbclass.Database = "Tables"
dbclass.ConnectionType = SqlServer
dbclass.DataSource = "E45c7642"
dbclass.UserId = Application.UserName
connOk = dbclass.OpenConnection(False, True)
If connOk = False Then
MsgBox "Cannot connect"
Else
MsgBox "The server is connected"
End If
End Sub
Finally I found the problem for my second code. As I wrote before, in my alternative code (second code), I didn't get any error at all in VBA, but it didn't save my table into the server.
Now I know the reason, because my real value was in "comma" format, but the server saved the value in "dot" format. So I added Str(value) to convert the "comma" value to the "dot" value, and it works now:
....
SQL = "INSERT INTO Table_test (Column1) VALUES (" & Str(result(1)) & ")"
dbclass.ExecuteSQL SQL
End Sub

Query database through Excel VBA

I am a beginner in Excel VBA. I want to query data from Teradata database and give the output into the rows of an excel sheet. When i write the below code:
Private Sub CommandButton1_Click()
Dim conn As Connection
Dim rec1 As Recordset
Dim thisSql As String
Set conn = New Connection
conn.Open "Driver=Teradata; DBCName=" & DBCName & ";UID=" & UID & ";PWD=" & PWD
thisSql = "simple select qyery here"
With .QueryTables.Add(Connection:=conn, Destination:=.Range("A1"))
.Sql = thisSql
.Name = "data"
.FieldNames = True
.Refresh BackgroundQuery:=False
End With
End Sub
I am getting the error saying 'Compiler error: User-defined type not defined'
how to overcome this error? Do i need to include anything in the code?
Please help
I am using MSVisualBasic 6.5 editor
Hi I guess it would need a recordset as the connection object when using QueryTables.Add.
I modified your code and tried it as following:
Dim conn As adodb.Connection
Dim rec1 As adodb.Recordset
Dim thisSql As String
Set conn = New adodb.Connection
conn.Open your_connection_string
thisSql = "your query here"
Set rec1 = New adodb.Recordset
rec1.Open thisSql, conn
With Sheet3.QueryTables.Add(Connection:=rec1, Destination:=Sheet3.Range("A1"))
.Name = "data"
.FieldNames = True
.Refresh BackgroundQuery:=False
End With

Resources