使用单元格作为参数,使用SQL在Excel中创建参数化查询

时间:2013-07-02 20:21:46

标签: sql database excel where-clause parameterized-query

所以在MS Excel中我从SQL Server的数据库中导入了一个表。我想创建一个参数化查询,其中有两个单元格。假设这两个细胞是G1和G2。 G1采用参数/类别,G2从参数/类别中获取值并查询您导入的表(实质上是从单元格输入动态的WHERE子句)。有人能告诉我怎么做吗?

1 个答案:

答案 0 :(得分:1)

编辑:根据聊天会话,我们发现第一个参数是要搜索的列,第二个参数是要过滤的值。


您可以通过过滤导入的表格来执行您想要的操作。

使用以下代码作为模板。修改它以引用正确的工作表和范围。

Sub FilterByParameter()
    Dim wb As Workbook
    Dim dataSheet As Worksheet
    Dim parameterSheet As Worksheet
    Dim rng As Range
    Dim filterColumn As Long
    Dim filterValue As String

    Set wb = ThisWorkbook
    ' sheet that contains your table
    Set dataSheet = wb.Sheets("Sheet1")
    ' sheet that contains your parameters
    Set parameterSheet = wb.Sheets("Sheet2")
    ' range that contains your table, hard-coded here
    ' but can easily be set dynamically
    Set rng = dataSheet.Range("A1:F78")

    ' get the column you are searching
    filterColumn = parameterSheet.Range("G1").Value

    ' get the value you want to filter on
    filterValue = parameterSheet.Range("G2").Value

    ' turn off autofilters if set
    dataSheet.AutoFilterMode = False

    ' autofilter using your column and filter
    rng.AutoFilter field:=filterColumn, Criteria1:=filterValue

    ' now you can do whatever you want to with the rows
    ' that remain after the autofilter was applied
End Sub

有关如何使用可见行的示例,请参阅Efficient way to delete entire row if...