Get Data from SQL DB to Excel using VBA script (Macros)
create one button in Excel sheet "Get Data". open sheet in Design view mode. right click on button and select "View Code" option in excel. it will open "Visual Basics" coding window.
My button event is "Private Sub btnGetData_Click()".
please follow the code. for getting the data from SQL db to Excel.
before execution of this code we need to add ADODB class reference in this Visual Basics.
ADD Reference:
in Visual Source window click on Tools--> References --> select "Microsoft ActiveX Data Objects 2.6 Library" in this case i am using Microsoft office 2007 version.
My button event is "Private Sub btnGetData_Click()".
please follow the code. for getting the data from SQL db to Excel.
before execution of this code we need to add ADODB class reference in this Visual Basics.
ADD Reference:
in Visual Source window click on Tools--> References --> select "Microsoft ActiveX Data Objects 2.6 Library" in this case i am using Microsoft office 2007 version.
Private Sub btnGetData_Click()
If
Range("C1") = "" Then
MsgBox
("Project number required.")
Exit
Sub
End
If
Dim
SQLConn As ADODB.Connection
Dim
SQLData As ADODB.Recordset
Set
SQLConn = CreateObject("ADODB.Connection")
SQLConn.Open
"provider =sqloledb; Data Source = SampleDataSource; Initial Catalog =
Pubs; User Id = Prasad; Password = Prasad@123;"
Set
SQLData = CreateObject("ADODB.Recordset")
With
SQLData
'
Assign the Connection object.
.ActiveConnection
= SQLConn
'
Extract the required records.
.Open
"SELECT [ProjectNo],[Unit],[Customer],[Location],[Project Eng],[Project
Eng Loc],[Project Manager],[Team Leader],[Process Eng] FROM [Project] WHERE
[ProjectNo]='" & Range("C1") & "'"
'
Copy the records into cell A1 on Sheet1.
If
SQLData.EOF Then
MsgBox
("File Not Found.")
Else
SQLData.MoveFirst
Sheet2.Range("C2").Value
= SQLData.Fields.Item("Unit")
Sheet2.Range("C3").Value
= SQLData.Fields.Item("Customer")
Sheet2.Range("C4").Value
= SQLData.Fields.Item("Location")
Sheet2.Range("C6").Value
= SQLData.Fields.Item("Project Eng")
Sheet2.Range("C7").Value
= SQLData.Fields.Item("Project Eng Loc")
Sheet2.Range("F5").Value
= SQLData.Fields.Item("Project Manager")
Sheet2.Range("F6").Value
= SQLData.Fields.Item("Team Leader")
Sheet2.Range("F7").Value
= SQLData.Fields.Item("Process Eng")
End
If
'
Tidy up
.Close
End
With
SQLConn.Close
Set
SQLData = Nothing
Set
SQLConn = Nothing
End Sub
for more SharePoint related Posts please visit "sharepointruler.blogspot.com" blog.
Comments
Post a Comment