query data from SQL server using VBA, assign it to a variable

spyla

New Member
Joined
Jan 18, 2011
Messages
16
Hi,

I using excel 2010 in Windows 7. I would like to query a SQL database using VBA and retrieve data and assign the data to a variable. currently I have been able write the following code


Code:
Sub Macro2()
'
' Macro2 Macro
'
'
    With ActiveSheet.ListObjects.Add(SourceType:=0, Source:= _
        "ODBC;DRIVER=SQL Server;SERVER=PNWEBSERV01;UID=pnxlreader;PWD=LimsPass01;APP=Microsoft Office 2010;WSID=PNDTP056V64;DATABASE=PNLMDB" _
        , Destination:=Range("$C$6")).QueryTable
        .CommandText = Array( _
        "SELECT Samples.Date_Sampled" & Chr(13) & "" & Chr(10) & "FROM PNLMDB.dbo.Samples Samples" & Chr(13) & "" & Chr(10) & "WHERE (Samples.Sample_Num='034223-02')" _
        )
        .RowNumbers = False
        .FillAdjacentFormulas = False
        .PreserveFormatting = True
        .RefreshOnFileOpen = False
        .BackgroundQuery = False
        .RefreshStyle = xlInsertDeleteCells
        .SavePassword = False
        .SaveData = True
        .AdjustColumnWidth = True
        .RefreshPeriod = 0
        .PreserveColumnInfo = True
        .ListObject.DisplayName = "Table_Query_from_pnweb01"
        .Refresh BackgroundQuery:=False
    End With
 
End Sub
but the problem with this code is that it puts the data on the sheet with column name on C6 and date on C7 but instead of being put on a sheet, I want to assign the query result to variable in VBA so that I can manipulate it. Not sure How to change the destination to a variable

thanks
 

Excel Facts

Save Often
If you start asking yourself if now is a good time to save your Excel workbook, the answer is Yes
How about:-
Code:
    End With
 
[COLOR=red][B]    column_name = ActiveSheet.Range("C6")[/B][/COLOR]
[COLOR=red][B]    the_date = ActiveSheet.Range("C7")[/B][/COLOR]
 
End Sub
 
Upvote 0
How about:-
Code:
    End With
 
[COLOR=red][B]   column_name = ActiveSheet.Range("C6")[/B][/COLOR]
[COLOR=red][B]   the_date = ActiveSheet.Range("C7")[/B][/COLOR]
 
End Sub


this is going to be part of big excel workbook and lot of VBA code. Would like to avoid putting data on to a sheet then delete after assigning it. Would also like to assign data to an array if I pull more than a single value
 
Upvote 0
I suggested that because it would have been a trivial change to your existing code. Copying data from the worksheet to an array would not have been very much more complicated.

My only other suggestion would be to establish an ADO connection to the database and pull the data directly into a variable.
 
Upvote 0
I suggested that because it would have been a trivial change to your existing code. Copying data from the worksheet to an array would not have been very much more complicated.

My only other suggestion would be to establish an ADO connection to the database and pull the data directly into a variable.


never used ADO, can you guide me some examples or books or any other resources
 
Upvote 0
I'm not the best person to ask - I've only ever used it to get at Access databases. At its simplest, for a single record:-
Code:
[FONT=Courier New][SIZE=1]Option Explicit[/SIZE][/FONT]
[FONT=Courier New][SIZE=1][/SIZE][/FONT] 
[FONT=Courier New][SIZE=1]Private Sub SearchSingle()[/SIZE][/FONT]
[FONT=Courier New][SIZE=1][/SIZE][/FONT] 
[FONT=Courier New][SIZE=1]  Dim dbData As DAO.Database
  Dim rsData As DAO.Recordset
  
  Set dbData = DAO.OpenDatabase("database.mdb")
  Set rsData = dbData.OpenRecordset("SELECT Forename, Surname FROM tblMembers WHERE EmpNum=123456;")[/SIZE][/FONT]
[FONT=Courier New][SIZE=1]  MsgBox "Employee 123456 is " & rsData!Forename & " " & rsData!Surname, vbOKOnly + vbInformation
  
  rsData.Close
  
End Sub[/SIZE][/FONT]

For multiple records:-
Code:
[FONT=Courier New][SIZE=1]Private Sub SearchMulti()[/SIZE][/FONT]
[FONT=Courier New][SIZE=1]  
  Dim dbData As DAO.Database
  Dim rsData As DAO.Recordset
  
  Set dbData = DAO.OpenDatabase("database.mdb")
  Set rsData = dbData.OpenRecordset("SELECT * FROM tblMembers WHERE Surname LIKE 'smi*';")[/SIZE][/FONT]
[FONT=Courier New][SIZE=1]  Do Until rsData.EOF
    MsgBox rsData!EmpNum & ": " & rsData!Surname & ", " & rsData!Forename, vbOKOnly + vbInformation
    rsData.MoveNext
  Loop
  
  rsData.Close
  
End Sub[/SIZE][/FONT]

As I said, this is for connecting to an Access database. How you make the connection to your own database I'm afraid I don't know.

Time to hit Google, perhaps?
 
Upvote 0

Forum statistics

Threads
1,217,352
Messages
6,136,058
Members
449,987
Latest member
lil_Sassy

We've detected that you are using an adblocker.

We have a great community of people providing Excel help here, but the hosting costs are enormous. You can help keep this site running by allowing ads on MrExcel.com.
Allow Ads at MrExcel

Which adblocker are you using?

Disable AdBlock

Follow these easy steps to disable AdBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the icon in the browser’s toolbar.
2)Click on the "Pause on this site" option.
Go back

Disable AdBlock Plus

Follow these easy steps to disable AdBlock Plus

1)Click on the icon in the browser’s toolbar.
2)Click on the toggle to disable it for "mrexcel.com".
Go back

Disable uBlock Origin

Follow these easy steps to disable uBlock Origin

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back

Disable uBlock

Follow these easy steps to disable uBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back
Back
Top