I know this is probably easy but I have not been able to get it figured out. I have two sheets....Input and Output. I have a sql query (using MS Query) that returns the correct data onto 'Output' when I have filters hardcoded into my Where clause. What I want to do is have an input cell(s) on 'Input' sheet and pass the value(s) to the query to populate the 'Output' sheet. In the code below, there are two lines in red. If I run using the first line with hardcoded sample id's, it works fine and puts the data to Output. If I run trying to reference the cell D3 on the input sheet to pass sample id 2154150, it fails. What am I doing wrong? Thanks.
Also, if the user wants to pass multiple sample id's, how would I accomplish this. I would imagine I could have them input each sample id in a different cell and then range it or have them input the samples in one cell separated by commas.
Also, if the user wants to pass multiple sample id's, how would I accomplish this. I would imagine I could have them input each sample id in a different cell and then range it or have them input the samples in one cell separated by commas.
Code:
Dim cn As ADODB.Connection
Dim rs As ADODB.Recordset
Dim i As Integer
Dim strSQL As String
Dim UserName As String
Set cn = New ADODB.Connection
Set rs = New ADODB.Recordset
cn.Open ( _
"Provider=SQLOLEDB; " & _
"MyDataSource; " & _
"MyDataBase; " & _
"Trusted_Connection=yes")
If (cn.State <> 1) Then
intResult = MsgBox("Could not connect to the database. Check your user name and password." & vbCrLf & Error(Err), 16, "Refresh Data")
Else
strSQL = "SELECT " & vbCrLf
strSQL = strSQL & "Distinct Sample_Id, " & vbCrLf
strSQL = strSQL & "Unit_Number, " & vbCrLf
strSQL = strSQL & "Unit_Description, " & vbCrLf
strSQL = strSQL & "Sample_Time, " & vbCrLf
strSQL = strSQL & "Sample_Point_Number, " & vbCrLf
strSQL = strSQL & "Sample_Point, " & vbCrLf
strSQL = strSQL & "Profile_Number " & vbCrLf
strSQL = strSQL & " " & vbCrLf
strSQL = strSQL & "From dbo.LAB_TestResults " & vbCrLf
[COLOR=#ff0000]strSQL = strSQL & "Where Sample_Id in ('2154150','2154149') " & vbCrLf
'strSQL = strSQL & "Where Sample_Id = ActiveWorkbook.Sheets("Input").Range("$D3") " & vbCrLf[/COLOR]
strSQL = strSQL & "ORDER BY Unit_Number, Unit_Description, Sample_Time, Sample_Point_Number, Sample_Point, Profile_Number "
rs.Open strSQL, cn
If rs.State = 1 Then
ActiveWorkbook.Sheets("Output").Activate
ActiveSheet.Cells.ClearContents
For i = 0 To rs.Fields.Count - 1
ActiveSheet.Cells(1, i + 1).Value = rs.Fields(i).Name
Next i
ActiveSheet.Range(ActiveSheet.Cells(1, 1), ActiveSheet.Cells(1, rs.Fields.Count)).Font.Bold = True
ActiveSheet.Range("A2").CopyFromRecordset rs
'Auto-fit up to 26 columns
ActiveSheet.Columns("A:" & Chr(64 + rs.Fields.Count)).AutoFit
rs.Close
End If
End If
End Sub