我正在尝试在Excel VBA中创建一个SQL查询,该查询将基于Excel中单元格的参数在Access中创建一个表。通常,我可以使用执行查询在数据库中运行一个预先构建的查询,但是由于我需要根据输入到单元格中的参数进行修改,因此我需要这样做。该参数仅适用于Where条件。对于此示例,我们可以说它也在选择固定字段“ Sales”和“ Product”,而“ Where”字段是“ Model”。由于遇到该表已经存在的错误,我还需要删除具有相同名称的现有表。 VBA代码的外观如何?
Step 1: Delete table with the same name
Step 2: Create a new table in Access with the "Where" criteria pointing to a cell.
Sub CreateTable()
On Error GoTo SubError
Const DbLoc As String = "C:\Folder to Excel\Database1.accdb"
Dim db As DAO.Database
Dim rs As DAO.Recordset
Dim xlBook As Workbook
Dim xlSheet As Worksheet
Dim recCount As Long
Dim SQL As String
Set xlBook = ActiveWorkbook
Set xlSheet = xlBook.Worksheets(1)
Set db = OpenDatabase(DbLoc)
SQL = "SELECT Sales, Product " & _
"FROM Table1 " & _
"WHERE Model IN (1, 2);"
如果我可以将参数提供给现有的make表查询,我也将很高兴!