I have an example in C# code, but it is using streamWriter. It must be involving with FileSystemObject rite. If yes, what are methods should I use? I want to code using VBScript WSH, and my database is MS SQL Server 2005.
Any solution, references, or guide are helpful.
using (StreamWriter tw = File.AppendText("c:\\INMS.txt"))
{
using (SqlDataReader reader = cmd.ExecuteReader())
{
tw.WriteLine("id, ip address, message, datetime");
while (reader.Read())
{
tw.Write(reader["id"].ToString());
tw.Write(", " + reader["ip"].ToString());
tw.Write(", " + reader["msg"].ToString());
tw.WriteLine(", " + reader["date"].ToString());
}
tw.WriteLine("Report Generate at : " + DateTime.Now);
tw.WriteLine("---------------------------------");
tw.Close();
reader.Close();
}
}
In VBScript you need ADODB objects and the FileSystemObject from the Scripting library. Something akin to:-
Dim conn: Set conn = CreateObject("ADODB.Connection")
conn.Open "an ole DB mysql connection string", usernameIfneeded, passwordIfNeeded
Dim cmd : Set cmd = CreateObject("ADODB.Command")
Set cmd.ActiveConnection = conn
cmd.CommandText = "your SQL code here"
cmd.CommantType = 1 ''# adCmdText Command text is a SQL query
Dim rs : Set rs = cmd.Execute
Dim fs : Set fs = CreateObject("Scripting.FileSystemObject")
Dim textStream : Set textStream = fs.OpenTextFile("c:\inms.txt", 8, True)
textStream.WriteLine "id, ip address, message, datetime"
Do Until rs.EOF
textStream.Write rs("id") & ","
textStream.Write rs("ip") & ","
textStream.Write rs("msg") & ","
textStream.WriteLine rs("date")
rs.MoveNext
Loop
textStream.Close
rs.Close
conn.Close
Related
I have multiple SQL queries that I build in PowerQuery.
How ever I would like to code those in VBA.
But after internet search, I still can not find my way to connect properly to the SQL tables.
I have problem in my connections string I suppose.
Please advice.
Attached is the PowerQuery querie.
Let me know please.
let
Source = Sql.Databases("EU002VM0353"),
EPV2P9028 = Source{[Name="EPV2P9053"]}[Data],
dbo_vw_pbi_01_fact_inspection_state = EPV2P9053{[Schema="dbo",Item="vw_pbi_01_fact_inspection_state"]}[Data],
#"Filtered Rows" = Table.SelectRows(dbo_vw_pbi_01_fact_inspection_state, each ([QCF Is required] = true) and ([Is NA] = false) and ([WS status] = "Active")),
If you want to get data directly from sql server to your excel sheet, you can use this piece of code:
'Define variables
Public con As Object, rs As Object, cmd As Object
Public Const provider As String = "SQLOLEDB"
Public Const server As String = "ServerName_or_IP_Adress"
Public Const database As String = "Database_Name"
Public Const serverUser As String = "ServerUser_(sa)"
Public Const serverPass As String = "xxx"
Public Const sheetName As String = "Query_Output_Sheet_Name"
' "Microsoft ActiveX Data Objects 2.8 Library" reference must be selected
Private Sub Query()
Dim con As ADODB.Connection
Dim cmd As ADODB.Command
Dim rs As ADODB.Recordset
Dim ws As Worksheet
Set ws = Sheets(sheetName)
Set con = New ADODB.Connection
con.ConnectionString = _
"Provider=" & provider & ";" & _
"Data Source=" & server & ";" & _
"Initial Catalog=" & database & ";" & _
"User ID=" & serverUser & ";" & _
"Password=" & serverPass & ";" & _
"Trusted_Connection=yes;" & _
"DataTypeCompatibility=80;"
con.Open
Dim Query As String
Query = "Select * from TableName"
Set cmd = New ADODB.Command
cmd.ActiveConnection = con
cmd.CommandTimeout = 600
cmd.CommandText = Query
Set rs = cmd.Execute(, , adCmdText)
If rs.EOF = False Then ws.Cells(1, 1).CopyFromRecordset rs
rs.Close
con.Close
Set rs = Nothing
Set cmd = Nothing
Set con = Nothing
End Sub
Connection variables defined as public, so you can call them from other modules or userforms. You just need to fill variables and sheet name (which you want to get the data)
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
How to execute special SQL Server stored procedure through Excel VBA? Special because it does not return rows like this procedure:
select * from tab1
How to execute the procedure which let's say prepares reports, like this one:
select *
into tab2
from tab1
which does not return any rows.
I am using this VBA code:
Dim cnn As Object
Set cnn = CreateObject("ADODB.Connection")
Dim cmd As Object
Set cmd = CreateObject("ADODB.Command")
Dim rs As Object
Set rs = CreateObject("ADODB.Recordset")
Dim ConnectionString As String
cnn.ConnectionString = "driver={SQL Server};server=MYSERVERNAME;Database=MYDATABASE;Trusted_Connection=yes;"
cnn.Open
Sql = "EXEC [dbo].[Procedure_make_report] 'param1'"
Set rs = cnn.Execute(Sql)
I get the error:
Runtime error 2147217900
I found a clue here:
http://www.vbforums.com/showthread.php?541498-RESOLVED-runtime-error-2147217900-(80040e14)-incorrect-syntax-error
but I do not know what action query is.
Based on comments of Rory and Tom, I leave the answer which works.
Dim cnn As Object
Set cnn = CreateObject("ADODB.Connection")
Dim cmd As Object
Set cmd = CreateObject("ADODB.Command")
cmd.CommandType = 1 ' adCmdText
cmd.CommandTimeout = 120 ' number of seconds to time out
Dim ConnectionString As String
cnn.ConnectionString = "driver={SQL Server};server=MYSERVERNAME;Database=MYDATABASE;Trusted_Connection=yes;"
cnn.Open
Dim SQL As String
SQL = "EXEC [dbo].[Procedure_make_report] 'param1'"
cnn.Open
cmd.CommandText = SQL
cmd.ActiveConnection = cnn
cmd.Execute
If Not cnn Is Nothing Then
cnn.Close
Set cnn = Nothing
End If
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
I am making a .MDB file which include a ms access database and a form made with vb 6. I am using ms access 2000, and I need to connect to both my local database in the MDB, and a remote MS SQL 2005 database.
In the below code, I can use a msgbox to display the value return from the result set, but when try to output it in a textBox, e.g: txtStatus.Value = txtStatus.Value & rstRecordSet.Fields(1) & vbCrLf, it just hangs. And the method show in the original example from the tutorial got a method of Debug.Print something, but it turns out didn't do anything which I can see. I mean, VB doesn't have a console panel, where will the print statement goes to?
The code with got error:
Function Testing()
On Error GoTo Error_Handling
Dim conConnection As New ADODB.Connection
Dim cmdCommand As New ADODB.Command
Dim rstRecordSet As New ADODB.Recordset
conConnection.ConnectionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" & _
App.Path & "\" & CurrentDb.Name & ";"
conConnection.CursorLocation = adUseClient
With cmdCommand
.ActiveConnection = conConnection
.CommandText = "SELECT * FROM Opt_In_Customer_Record;"
.CommandType = adCmdText
End With
With rstRecordSet
.CursorType = adOpenStatic
.CursorLocation = adUseClient
.LockType = adLockOptimistic
.Open cmdCommand
End With
If rstRecordSet.EOF = False Then
rstRecordSet.MoveFirst
Do
MsgBox "Record " & rstRecordSet.AbsolutePosition & " " & _
rstRecordSet.Fields(0).Name & "=" & rstRecordSet.Fields(0) & " " & _
rstRecordSet.Fields(1).Name & "=" & rstRecordSet.Fields(1)
rstRecordSet.MoveNext
Loop Until rstRecordSet.EOF = True
End If
conConnection.Close
Set conConnection = Nothing
Set cmdCommand = Nothing
Set rstRecordSet = Nothing
Exit Function
Error_Handling:
MsgBox "Error during function Testing!"
Exit Function
End Function
I thought it was a joke at the beginning ;-)
Anyway I assume you're talking about ADO, as in your title.
Here you can find stuff.
This site will help you with the connection strings for different database.
The difference between access and sql server using ADO it is exactly the connection string.
I would suggest you to avoid Remote Data Controls cause make your life simpler at the beginning but then you have to struggle with them cause they don't work properly.
This is an example of connection and fetch of data:
Dim cnn As New ADODB.Connection
Dim cmd As New ADODB.Command
Dim strSql As String
cnn.ConnectionString = _
"Provider=Microsoft.Jet.OLEDB.4.0;" & _
"Data Source=m:\testdbSource\testSource.mdb;" & _
"User Id=admin;Password=;"
cnn.Open
cmd.ActiveConnection = cnn
cmd.CommandType = adCmdText
cmd.CommandText = "select * from tblSource"
cmd.Execute
Set cmd = Nothing
cnn.Close
Set cnn = Nothing
This sample works for me:
Function Testing()
On Error GoTo Error_Handling
Dim MyDb As String
Dim conConnection As New ADODB.Connection
Dim cmdCommand As New ADODB.Command
Dim rstRecordSet As New ADODB.Recordset
MyDb = "db1.mdb"
With conConnection
.Provider = "Microsoft.Jet.OLEDB.4.0"
.ConnectionString = App.Path & "\" & MyDb
.Open
End With
With cmdCommand
.ActiveConnection = conConnection
.CommandText = "SELECT * FROM Opt_In_Customer_Record;"
.CommandType = adCmdText
End With
With rstRecordSet
.CursorType = adOpenStatic
.CursorLocation = adUseClient
.LockType = adLockOptimistic
.Open cmdCommand
End With
Do While Not rstRecordSet.EOF
MsgBox "Record " & rstRecordSet.AbsolutePosition & " " & _
rstRecordSet.Fields(0).Name & "=" & rstRecordSet.Fields(0) & " " & _
rstRecordSet.Fields(1).Name & "=" & rstRecordSet.Fields(1)
rstRecordSet.MoveNext
Loop
conConnection.Close
Set conConnection = Nothing
Set cmdCommand = Nothing
Set rstRecordSet = Nothing
Exit Function
Error_Handling:
MsgBox "Error during function Testing!"
MsgBox Err.Description
End Function