2

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

4

1 回答 1

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

有关如何使用可见行的示例,请参阅删除整行的有效方法如果...。

于 2013-07-02T20:35:38.990 回答