needhelpwithvba
New Member
- Joined
- Aug 5, 2011
- Messages
- 4
I'm trying to export a specific row from Access into Excel. In this case, I have a code that looks to cell B2 and B3 in Excel to define the criteria of what to look for in Access. My code looks like this:
Sub NumberPets()
Const strDb As String = "C:\Pets.mdb"
'looks to cell B2 and B3 for criteria on #dogs and #cats
Const strQry As String = "SELECT * from [tblPets] WHERE ([tblPets].[Dogs]=Range("B2").Value) And ([tblPets].[Cats]=Range("B3").Value)"
Dim rs As ADODB.Recordset
Dim cn As ADODB.Connection
Set cn = New ADODB.Connection
cn.Open "Provider=Microsoft.Ace.OLEDB.12.0; Persist Security Info = False; " & "Data Source=C:\Pets.mdb;"
Set rs = New ADODB.Recordset
With rs
Set .ActiveConnection = cn
.Open strQry
End With
'pastes data to cell B4
Worksheets("Data").Range("B4").CopyFromRecordset rs
rs.Close: cn.Close
Set rs = Nothing: Set cn = Nothing
End Sub
I get an error message that says "Compile error: Syntax error." If I replace Range("B2").Value with 1 and Range("B3").Value with 0 the code works fine. Any help would be greatly appreciated!
Sub NumberPets()
Const strDb As String = "C:\Pets.mdb"
'looks to cell B2 and B3 for criteria on #dogs and #cats
Const strQry As String = "SELECT * from [tblPets] WHERE ([tblPets].[Dogs]=Range("B2").Value) And ([tblPets].[Cats]=Range("B3").Value)"
Dim rs As ADODB.Recordset
Dim cn As ADODB.Connection
Set cn = New ADODB.Connection
cn.Open "Provider=Microsoft.Ace.OLEDB.12.0; Persist Security Info = False; " & "Data Source=C:\Pets.mdb;"
Set rs = New ADODB.Recordset
With rs
Set .ActiveConnection = cn
.Open strQry
End With
'pastes data to cell B4
Worksheets("Data").Range("B4").CopyFromRecordset rs
rs.Close: cn.Close
Set rs = Nothing: Set cn = Nothing
End Sub
I get an error message that says "Compile error: Syntax error." If I replace Range("B2").Value with 1 and Range("B3").Value with 0 the code works fine. Any help would be greatly appreciated!