I use VBA Word with Access, to create/store medical visit notes for Nursing homes.
The following is an example of how I get data out of Access (obviously picking up mid-Sub). This is populating a ComboBox in Word which gives me a list of all my patients, it is working great!
'....
Set Conn = New ADODB.Connection
Set rs = New ADODB.Recordset
strConn = ActiveDocument.CustomDocumentProperties("strConn").Value
Conn.Open (strConn)
qry = "SELECT * FROM tblPatientInfo ORDER BY LastName, Firstname"
rs.Open qry, Conn, adOpenKeyset
rs.MoveFirst
x = 0
While Not rs.EOF
F1.ComboDashPtList.AddItem
F1.ComboDashPtList.List(x, 0) = rs.Fields("LastName").Value & ""
F1.ComboDashPtList.List(x, 1) = rs.Fields("FirstName").Value & ""
F1.ComboDashPtList.List(x, 2) = Format(rs.Fields("DOB").Value, "MM\/dd\/yyyy") & ""
F1.ComboDashPtList.List(x, 3) = rs.Fields("MedNumber").Value & ""
rs.MoveNext
x = x + 1
Wend
rs.Close
Exit Sub`
'....
This is an example of how I send my data back to Access (again picking up mid-Sub).
` Set Conn = New ADODB.Connection
Set rs = New ADODB.Recordset
Conn.Open (strConn)
rs.Open strDBPtInfo, strConn, adOpenKeyset, adLockOptimistic, adCmdTable
rs.AddNew
rs!MedNumber = strMedNum
rs!LastName = strLastName
rs!Firstname = strFirstName
rs!DOB = dtDOB
rs.Update `
'....
Sometimes I need to completely overwrite or add to a specific field in a certain Access table. For years 'someone may have an allergy to penicillin, but suddenly they are also allergic to codeine, so that has to 'be updated. This is the approach I've taken but I keep getting an error:
'....
` Set Conn = New Connection
Set rs = New Recordset
Conn.Open (strConn)
strUpdateqry = "SELECT * FROM tblMedHxInfo WHERE MedNumber = " & Chr(34) & strMedNum & Chr(34) & ""
rs.Open strUpdateqry, strConn, adOpenKeyset
rs!Allergies = "Penicillin, Codeine"
rs.Update
If rs.State = 1 Then rs.Close
If Conn.State = 1 Then Conn.Close
Set rs = Nothing
Set Conn = Nothing`
....
This is the Error:
"Run-time error '3251': Current Recordset does not support updating.
This may ne a limitation of the provider, or of the selected locktype"
'Any help would be greatly appreciated!
'Thanks,
'Derek
'I've tried using the recordset to create a temporary table and then use that to update but it's getting over my head
Explicitly declare connection and recordset type. Then Set lines are not required.
Set the lock type argument.
Reference connection object not string variable for opening recordset.
Dim cn As ADODB.Connection, rs As ADODB.Recordset
cn.Open (strConn)
strUpdateqry = "SELECT * FROM tblMedHxInfo WHERE MedNumber = " & Chr(34) & strMedNum & Chr(34)
rs.Open strUpdateqry, cn, adOpenKeyset, adLockOptimistic
rs.Update "Allergies", "Penicillin, Codeine"
Or instead of opening recordset object for insert or update:
Dim cn As ADODB.Connection
cn.Open (strConn)
cn.Execute "UPDATE tblMedHxInfo SET Allergies = 'Penicillin, Codeine' WHERE MedNumber='" & strMedNum & "'"
Related
I'm trying to learn how to connect to a SQL Server DB from Excel DB. I've tried to reduce the code to dead simple to begin with. I've looked at several answers to related questions, however, I cannot figure out why this doesn't work. It executes all the way through. (The code shown here is somewhat anonymized.)
The query finds the database, because if the table name is invalid it throws an error. However it always returns record count = -1. I can eyeball the table in MSSMS and it has data. Same result for other tables in the DB.
Public Sub ADOtest1()
Dim Conn As ADODB.Connection
Dim rs As ADODB.Recordset
Dim strConnString As String
strConnString = "Provider='SQLOLEDB'" & ";" & _
"Data Source='XXX-XPS\SQLEXPRESS'" & ";" & _
"Initial Catalog='XXXXX'" & ";" & _
"Integrated Security='SSPI'"
Set Conn = New ADODB.Connection
Conn.Open strConnString
' the query finds the DB, because if the table name is incorrect, it throws an error
strSQLString = "SELECT * from t300_XXXX"
Set rs = Conn.Execute(strSQLString)
wrkRecordCount = rs.RecordCount
'--- just some test breakpoints
If wrkRecordCount = -1 Then
a = "" '--- code keeps arriving here
Else
a = ""
End If
rs.Close
Conn.Close
End Sub
Answer from Srinika below worked:
Set rs = Conn.Execute(strSQLString)
rs.Close
rs.CursorLocation = adUseClient
rs.Open
I'll post two examples, so please refer.
First Example
Sub ExampleSQL()
Dim cnn As ADODB.Connection
Dim rs As ADODB.Recordset
Dim strSQL As String
Set cnn = New ADODB.Connection
'Set the provider property to the OLE DB Provider for ODBC.
'cnn.Provider = "MSDASQL"
'cnn.Provider = "Microsoft.ACE.OLEDB.12.0"
'cnn.Provider = "MSOLAP"
'cnn.Provider = "SQLOLEDB.1"
' Open a connection using an ODBC DSN.
cnn.ConnectionString = "driver={SQL Server};" & _
"server=severname;uid=sa;pwd=password;database=test"
Set rs = New ADODB.Recordset
strSQL = "SELECT * FROM [your Table] "
rs.Open strSQL, cnn.ConnectionString, adOpenForwardOnly, adLockReadOnly, adCmdText
cnn.Open
If cnn.State = adStateOpen Then
Else
MsgBox "Sever is not connected!! "
Exit Sub
End If
If Not rs.EOF Then
With Ws
.Range("a4").CurrentRegion.ClearContents
For i = 0 To rs.Fields.Count - 1
.Cells(4, i + 1).Value = rs.Fields(i).Name
Next
.Range("a5").CopyFromRecordset rs
.Columns.AutoFit
End With
Else
MsgBox "No Data!!", vbCritical
End If
rs.Close
Set rs = Nothing
cnn.Close
Set cnn = Nothing
End Sub
Second Example
Sub getDataFromServer()
Dim con As New ADODB.Connection
Dim cmd As New ADODB.Command
Dim rs As New ADODB.Recordset
Dim i As Integer
con.ConnectionString = "Provider=SQLOLEDB.1;" _
& "Server=(local);" _
& "Database=TEST;" _
& "Integrated Security=SSPI;" _
& "DataTypeCompatibility=80;"
con.Open
Set cmd.ActiveConnection = con
cmd.CommandText = "SELECT * FROM [your Table]"
Set rs = cmd.Execute
Range("A1").CopyFromRecordset rs
con.Close
Set con = Nothing
End Sub
It dose not work [rs.RecordCount] on recordset made by [new ADODB.Recordset].
But it can work [rs.RecordCount] on recordset made by [CreateObject("ADODB.Recordset")].
By the way, it also dosen't work [rs.fields([integer])] on recordset made by [CreateObject("ADODB.Recordset")].
But it can work on [rs.fields([integer])] on recordset made by [new ADODB.Recordset]
How can I use two source([rs.fields([integer])] and [rs.RecordCount]) on one recordset?
Sub all_column()
Call connectDB
Dim strSql As String
Dim Syntax As String
Dim recordsAffected As Long
Dim nameOfTable As String
Dim numberOfRecord As Integer
Dim i, next_i As Integer
Set rsTable = CreateObject("ADODB.Recordset")
rsTable.CursorLocation = adUseClient
'This is query'
strSql = "show tables"
'Set recordset by [CreateObject("ADODB.Recordset")]'
'just for return of [.RecordCount]'
'Because of [.RecordCount] dose not work on [new ADODB.Recordset]'
Set rs = CreateObject("ADODB.Recordset")
rs.CursorLocation = adUseClient
rs.Open strSql, cn, adOpenStatic
numberOfRecord = rs.RecordCount
rs.Close
'Set recordset by [New ADODB.Recordset]'
'because of [.Fields(0)] dose not work on [CreateObject("ADODB.Recordset")]'
Set rs = New ADODB.Recordset
rs.Open strSql, cn, adOpenStatic
i = 2
Do While rs.EOF = False
nameOfTable = rs.Fields(0).Value
strSql = "DESC " + nameOfTable + ";"
rsTable.Open strSql, cn, adLockReadOnly
next_i = i + rsTable.RecordCount
Sheets("sheet1").Range("b" + CStr(i)).CopyFromRecordset rsTable
Sheets("sheet1").Range("a" + CStr(i) + ":a" + CStr(next_i - 1)).Value = nameOfTable
i = next_i
rsTable.Close
rs.MoveNext
Loop
rs.Close
cn.Close
End Sub
ADO = Microsoft Active X Data Objects 6.1 Library
SQL = 5.7.14-google-log (Google)
EXCEL = Microsoft Excel 2016 MSO (16.0.10228.20080)
I have code that is pulling in data from a SQL table, and using VB and a data validation List Box that allows the user to select a criteria then it should pull in the data associated with that criteria: but I am not getting any errors and it is running the code but not pulling in any data. Can someone let me know what I am doing wrong: Here is my example: I select scenario from the Data Validation List Box and get " No Records Returned" here is my code:
Dim conn As ADODB.Connection
Dim rs As ADODB.Recordset
Dim sConnString As String
Dim sSQL As String
Dim ceRg As Worksheet
Set ceRg = ThisWorkbook.Worksheets("RG Schedule")
If ceRg.FilterMode Then
ceRg.ShowAllData
End If
ceRg.Range("A3").ClearContents
' Create the connection string.
sConnString = "Provider=SQLOLEDB;Data Source=SQL\SQLEXPRESS;Initial Catalog=Sample;Trusted_Connection=yes;"
' Create the Connection and Recordset objects.
Set conn = New ADODB.Connection
Set rs = New ADODB.Recordset
' Open the connection and execute.
conn.Open sConnString
sSQL = "SELECT [ORDER #],[SCENARIO],[LOCATION],[FORM],[STATUS],"
sSQL = sSQL & "CAST([Date Ordered] as date),"
sSQL = sSQL & "[Design],[Cost],"
sSQL = sSQL & "CAST([Critical Obligation Date] as date),"
sSQL = sSQL & "[MGMT_APPROVED],[AUTHORIZATION_Y_N],[CUSTOMER]"
sSQL = sSQL & "FROM [dbo].[vwRG_Schedule]"
sSQL = sSQL & "WHERE [SCENARIO] = '" & Scenario & "' "
sSQL = sSQL & "ORDER BY [ORDER #]"
Set rs = conn.Execute(sSQL)
' Check we have data.
If Not rs.EOF Then
' Transfer result.
ceRg.Range("A3").CopyFromRecordset rs
' Close the recordset
rs.Close
Else
MsgBox "Error: No records returned.", vbCritical
End If
' Clean up
If CBool(conn.State And adStateOpen) Then conn.Close
Set conn = Nothing
Set rs = Nothing
End Sub
I'm trying to create a VBA code that would connect to a specific database based on the user's input. E.g. if a user enters DB1 into the prompt, the code will run the following query: SELECT * FROM MyServerName.DB1.dbo.Table
Here is what I've got so far:
Dim conn As ADODB.Connection
Dim rs As ADODB.Recordset
Dim sConnString As String
Dim strSQL As String
Dim DB As Variant
DB = InputBox("Please enter the Database Name.")
sConnString = "Provider=SQLOLEDB;Data Source=MyServerName;" & _
"Integrated Security=SSPI;"
Set conn = New ADODB.Connection
Set rs = New ADODB.Recordset
' Unsuccessful attempt to use the Else/If statement:
if '" & DB & "' = "DB1" then
conn.Open sConnString
Set rs = conn.Execute("SELECT * FROM MyServerName.DB1.dbo.Table ;")
elseif '" & DB & "' = "DB2" then
conn.Open sConnString
Set rs = conn.Execute("SELECT * FROM MyServerName.DB2.dbo.Table ;")
else
MsgBox "No records returned. Enter the correct Database Name.", vbCritical
End If
If Not rs.EOF Then
Sheets("Sheet1").Range("A2").CopyFromRecordset rs
rs.Close
If CBool(conn.State And adStateOpen) Then conn.Close
Set conn = Nothing
Set rs = Nothing
End Sub
The connection itself is working just fine when I use the select statement without Else/If. Does anyone know how to fix this? Thanks so much!
You could just use the DB variable to decide which database to use
Set rs = conn.Execute("SELECT * FROM [MyServerName].[" & DB & "].dbo.table ;")
My code to retrieve value is as below:
Sub UploadData()
Dim rs As ADODB.Recordset
Set rs = New ADODB.Recordset
Dim cn As ADODB.Connection
Set cn = New ADODB.Connection
Dim strConn As String
Dim sql As String
strConn = "PROVIDER=SQLOLEDB;DATA SOURCE=.\sql2000;INITIAL CATALOG=EquityDB;INTEGRATED SECURITY=sspi;"
cn.Open strConn
sql = "select * from EquityDB.dbo.table1 where field1 = '" & Replace(Range("d1").Value, "'", "''") & "'"
rs.Open sql, cn, adOpenDynamic, adLockOptimistic
GetData = rs.Fields(0).Value
If Not GetData = "" Then
cn.Execute sql001
Else
cn.Execute sql002
End If
sql001 is an insert, and sql002 is an update
When I run the macro, I got error saying operation is not allowed when the record is open for the line
rs.Open sql, cn, adOpenDynamic, adLockOptimistic
If I change
If Not GetData = "" Then
to
If Not GetData Is Null Then
I get error saying "object required" with the line
If Not GetData Is Null Then
Any advice on how to fix the bug would be great!
To test if anything was returned into your recordset, instead of:
GetData = rs.Fields(0).Value
If Not GetData = "" Then
Use:
If not(rs.eof and rs.bof) then
This will return true if the recordset is not empty.