Reputation: 109
I have a problem with adding a button to a MS Access Form which would execute a query and open the results in a new window (in whatever format).
The two main problems are:
The below code unfortunately does not work.
Sub bQuery_Click()
Dim StrSQL As String
Dim username As String
username = Environ("USERNAME")
StrSQL = "SELECT EntryText, NameID FROM [I:\SharedDrive\Master DB.accdb;PWD=pwd;].Database WHERE NameID='" & username & "';"
DoCmd.TransferSpreadsheet acExport, acSpreadsheetTypeExcel12, StrSQL, "I:\SharedDrive\file1.xlsx"
End Sub
Upvotes: 0
Views: 418
Reputation: 107652
Simply create a query in Access and change the SQL with each button click:
SQL
SELECT EntryText, NameID
FROM [I:\SharedDrive\Master DB.accdb;PWD=pwd;].Database
WHERE NameID='xLokos';
VBA
Sub bQuery_Click()
Dim qdef As QueryDef
username = Environ("USERNAME")
StrSQL = "SELECT EntryText, NameID" _
& " FROM [I:\SharedDrive\Master DB.accdb;PWD=pwd;].Database" _
& " WHERE NameID='" & username & "';"
Set qdef = CurrentDb.QueryDefs("mySavedQuery")
qdef.SQL = strSQL
Set qdef = Nothing 'SAVES QUERY
DoCmd.TransferSpreadsheet acExport, acSpreadsheetTypeExcel12, _
"mySavedQuery", _
"I:\SharedDrive\file1.xlsx"
End Sub
Upvotes: 0
Reputation: 2341
Would you be able/willing to add the table you're querying as a linked table? That way, you can create the query in your front-end database, and just export that query, rather than having to hard-code SQL in VBA.
Adding the table as a linked table will expose the password on the TableDef
object, but it seems like you're already exposing the password in VBA. If you haven't already, you can lock down the database to make it hard for the user to open the VBA IDE (there are a number of strategies to do this, such as creating an ACCDE file, password-protecting the module file, and just locking down ribbons and keyboard shortcuts).
Upvotes: 1