Search

VBA and SQL Server - How to create connection to SQL Server Database from Excel. Part-8



Hello friends, all relevant materials for this topic/tutorial can be downloaded from here. Please support us by subscribing to our channel and sharing them with your friends.

If you have any questions/feedback/tutorial request, please you can email me directly vbaa2z.team@gmail.com or comment on YouTube Video (blog comments are not actively monitored).

https://www.youtube.com/watch?v=FNNQturTjX8&lc

Option Explicit

Sub sync_data_vba_sqlserver()

'-----------------------------
'Thanks for downloading the code. 
'Please visit our channel for a quick explainer on how to use this code.
'Feel free to update the code as per your need and also share with your friends.
'Download free codes from http://vbaa2z.blogspot.com
'Support our channel: youtube.com/vbaa2z
'Author: L Pamai (vbaa2z.team@gmail.com)
'-----------------------------

Dim conn As ADODB.Connection
Dim cs As String
Dim SQLstr As String
Dim x As Long
Dim fld As ADODB.Field

On Error GoTo errrrrr

Set conn = New ADODB.Connection
cs = "DRIVER=SQL Server;"
cs = cs & "DATABASE=TransacDb;"
cs = cs & "SERVER=LP-PC"

'Data Source=SQL Server;Initial Catalog=LP-PC;Persist Security Info=True;User ID=;Password=


conn.Open cs, "", ""

Dim rst As New ADODB.Recordset
Set rst = New ADODB.Recordset

SQLstr = "Select * From FlowTb;" ' WHERE county = 'Orleans';"

rst.Open SQLstr, conn, adOpenForwardOnly, adLockReadOnly

x = 0

Sheets("Sheet2").Select

For Each fld In rst.Fields
    Cells(1, x + 1).Value = fld.Name
    x = x + 1
Next fld

Range("A2").CopyFromRecordset rst
[a1] = Now()

rst.Close
Set rst = Nothing

conn.Close
Set conn = Nothing

Exit Sub
errrrrr:

Debug.Print Err.Number & ". " & Err.Description
conn.Close
Set conn = Nothing

End Sub

No comments:

Post a Comment

Note: only a member of this blog may post a comment.