Query database through Excel VBA - database

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

Related

ADO connection from Excel to SQL Server executes but returns no records

I have a spreadsheet from which I want to pass SQL script to my SQL server Database, both to retrieve records and run stored procedures.
Here's my code:
Sub ApendPickListData()
Dim SqlConn As New ADODB.Connection
Dim listID As Integer
Dim lists As New ADODB.Recordset
Dim SQLstr As String
SqlConn.ConnectionString = "Provider = 'SQLOLEDB';Server=MyServer\SQLEXPRESS;Database=MyDatabase;Uid=Username;PWD=Password;"
SqlConn.Open
'The following execution of a stored procedure works
SqlConn.Execute "Exec spListsInsertNew #Type = 'Picking', #Date ='" & Date & "'"
SQLstr = "SELECT ItemList.ItemNumber from ItemList"
'This method doesn't work
With lists
.ActiveConnection = SqlConn
.Source = SQLstr
.Open
Debug.Print .RecordCount
'prints -1 in the immediate window - no records
End With
'Neither does this method
Set lists = SqlConn.Execute(SQLstr)
Debug.Print lists.RecordCount
'prints -1 in the immediate window - no records
SqlConn.Close
End Sub
I feel like I'm missing something obvious. I've searched this site and others, found examples where this code should work. I've tested the select statement in SSMS and it works as expected.
Any help would be appreciated!
The code that worked was from Mark Balhoff's comment. Here it is:
Sub ApendPickListData()
Dim SqlConn As New ADODB.Connection
Dim listID As Integer
Dim lists As New ADODB.Recordset
Dim SQLstr As String
SqlConn.ConnectionString = "Provider = 'SQLOLEDB';Server=Myserver\SQLEXPRESS;Database=MyDB;Uid=Username;PWD=Password;"
SqlConn.Open
SQLstr = "select dbo.ItemList.ItemNumber from dbo.ItemList"
With lists
.ActiveConnection = SqlConn
.Source = SQLstr
.CursorLocation = adUseClient 'This was the key!
.Open
Debug.Print .RecordCount
End With
SqlConn.close
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

Change the text in a field with a VBA function

I'm currently working on a database in Access which has a table (Pro_Cons) who compares the pros and cons of different product-types. This table has 3 columns; Type (Product_type), Pros (Pro) and Cons.
For each of product-type I created a form which includes the pro- and the cons-field of the according type out of this table.
For adding new text to this fields I'm creating a VBA-function which is triggered by a button-click.
Because nothing worked as supposed to, I created the following function, which should only replace the Pro -field of the product type1 to change1.
Access doesnt throw an error, but nothing changes in the table.
Has someone an idea whats happening here?
Sub Change_Pos_Inf()
Dim db As DAO.Database
Dim rst As DAO.Recordset
Dim strSQL As String
Dim strSensortyp As String
Dim strNew As String
Set db = CurrentDb()
strProduct_type = "type1"
strNew = "change1"
strSQL = "SELECT Pro FROM Pro_Cons WHERE Product_type='strProduct_type';"
Set rst = db.OpenRecordset(strSQL, dbOpenDynaset)
With rst
If .RecordCount > 0 Then
.MoveFirst
.Edit
!Pro.Value = strNew
.Update
End If
End With
End Sub
I think your literal should be changed to reference a form control:
strSQL = "SELECT Pro FROM Pro_Cons WHERE Product_type='strProduct_type';"
Changes to:
strSQL = "SELECT Pro FROM Pro_Cons WHERE Product_type='" & Me!strProduct_type &
"'";
Please try the following code. It corrects your WHERE clause:
Sub Change_Pos_Inf()
Dim db As DAO.Database
Dim rst As DAO.Recordset
Dim strSQL As String
Dim strSensortyp As String
Dim strNew As String
Set db = CurrentDb()
strProduct_type = "type1"
strNew = "change1"
strSQL = "SELECT Pro FROM Pro_Cons WHERE Product_type= '" & strProduct_type & "';"
Set rst = db.OpenRecordset(strSQL, dbOpenDynaset)
With rst
If Not rst.EOF Then
.Edit
!Pro.Value = strNew
.Update
Else
MsgBox "No Record found!!"
End If
End With
rst.Close
Set rst = Nothing
End Sub

Update/Upload values from Excel to SQL Server Database

I’ve recently got into SQL Server, trying to build some query to return info (in Excel) from our ERP system (JobBoss) database. I was wondering:
Is there a way to update/change values in the SQL Server database from Excel?
For example, I have established a connection (in Excel) to our SQL Server already, and have a query that SELECTs certain values from specific tables to create a report. However, I was wondering if I can simply change the values in Excel then somehow “upload/synchronize” with the database?
If so, what are the options?
Thanks
Going from Excel to SQL Server? You have several options.
Setup looks link this:
Sub Rectangle1_Click()
'TRUSTED CONNECTION
On Error GoTo errH
Dim con As New ADODB.Connection
Dim rs As New ADODB.Recordset
Dim strPath As String
Dim intImportRow As Integer
Dim strFirstName, strLastName As String
Dim server, username, password, table, database As String
With Sheets("Sheet1")
server = .TextBox1.Text
table = .TextBox4.Text
database = .TextBox5.Text
If con.State <> 1 Then
con.Open "Provider=SQLOLEDB;Data Source=" & server & ";Initial Catalog=" & database & ";Integrated Security=SSPI;"
'con.Open
End If
'this is the TRUSTED connection string
Set rs.ActiveConnection = con
'delete all records first if checkbox checked
If .CheckBox1 Then
con.Execute "delete from tbl_demo"
End If
'set first row with records to import
'you could also just loop thru a range if you want.
intImportRow = 10
Do Until .Cells(intImportRow, 1) = ""
strFirstName = .Cells(intImportRow, 1)
strLastName = .Cells(intImportRow, 2)
'insert row into database
con.Execute "insert into tbl_demo (firstname, lastname) values ('" & strFirstName & "', '" & strLastName & "')"
intImportRow = intImportRow + 1
Loop
MsgBox "Done importing", vbInformation
con.Close
Set con = Nothing
End With
Exit Sub
errH:
MsgBox Err.Description
End Sub
Also, consider this option.
Sub UpdateTable()
Dim cnn As Object
Dim wbkOpen As Workbook
Dim objfl As Variant
Dim rngName As Range
Workbooks.Open "C:\Users\Excel\Desktop\Excel_to_SQL_Server.xls"
Set wbkOpen = ActiveWorkbook
Sheets("Sheet1").Select
Set rngName = Range(Range("A1"), Range("A1").End(xlToLeft).End(xlDown))
rngName.Name = "TempRange"
strFileName = wbkOpen.FullName
Set cnn = CreateObject("ADODB.Connection")
cnn.Open "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" & strFileName & ";Extended Properties=""Excel 12.0 Xml;HDR=Yes"";"
nSQL = "INSERT INTO [odbc;Driver={SQL Server};Server=Excel-PC\SQLEXPRESS;Database=[Northwind].[dbo].[TBL]]"
nJOIN = " SELECT * from [TempRange]"
cnn.Execute nSQL & nJOIN
MsgBox "Uploaded Successfully"
wbkOpen.Close
Set wbkOpen = Nothing
End Sub
Sub InsertInto()
'Declare some variables
Dim cnn As adodb.Connection
Dim cmd As adodb.Command
Dim strSQL As String
'Create a new Connection object
Set cnn = New adodb.Connection
'Set the connection string
cnn.ConnectionString = "Excel-PC\SQLEXPRESS;Database=Northwind;Trusted_Connection=True;"
'Create a new Command object
Set cmd = New adodb.Command
'Open the connection
cnn.Open
'Associate the command with the connection
cmd.ActiveConnection = cnn
'Tell the Command we are giving it a bit of SQL to run, not a stored procedure
cmd.CommandType = adCmdText
'Create the SQL
strSQL = "UPDATE TBL SET JOIN_DT = 2013-01-13 WHERE EMPID = 2"
'Pass the SQL to the Command object
cmd.CommandText = strSQL
'Open the Connection to the database
cnn.Open
'Execute the bit of SQL to update the database
cmd.Execute
'Close the connection again
cnn.Close
'Remove the objects
Set cmd = Nothing
Set cnn = Nothing
End Sub
See the link below for some additional ideas of how to get this done.
https://www.excel-sql-server.com/excel-sql-server-import-export-using-vba.htm#Introduction

"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

Resources