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
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
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
thanks