【问题标题】:condition sql statement with excel cell reference带有excel单元格引用的条件sql语句
【发布时间】:2013-10-09 17:43:48
【问题描述】:

我正在将一些 SQL 查询应用到电子表格中,并且无法最大限度地减少工作表/连接的数量。

我有 3 个场景,对于每个场景,我都使用相同的查询

 select *
 from ***scenario_table***
 where mycolumn > 100

现在我必须为不同的“scenario_table”执行 3 次,我真的想使用一个单元格作为参考(假设单元格 $A$1)

我想要这样的东西

 select *
 from
     case when [$A$1] = 1 ***scenario1_table***
     case when [$A$1] = 2 ***scenario2_table***
     case when [$A$1] = 3 ***scenario3_table***
  where mycolumn > 100

我知道有没有办法解决?

谢谢

【问题讨论】:

  • 你在哪里有 SQL 查询?列表、数据透视表、只是语句文本...?
  • excel -> 数据 -> 来自其他来源 -> 来自 MS 查询

标签: sql excel reference conditional cell


【解决方案1】:

此解决方案使用

假设您的单元格内容位于Sheet1!A1 中,并且您的工作簿中只有一个连接,请在Sheet1 中插入以下代码:

Private Sub Worksheet_Change(ByVal Target As Range)
    If Intersect(Target, Me.Range("A1")) Then
        Select Case Me.Range("A1").Value
            Case 1: SetTable ("Scenary1_Table")
            Case 2: SetTable ("Scenary2_Table")
            Case 3: SetTable ("Scenary3_Table")
        End Select
    End If
End Sub

Sub SetTable(ByVal TableName As String)
    With ThisWorkbook.Connections(1)
        .ODBCConnection.CommandText = "SELECT * FROM " & TableName
        .Refresh
    End With
End Sub

【讨论】:

  • 感谢您的代码。不幸的是,我的工作簿中有多个连接。
  • 好的,如果你能定义它,我们可以选择正确的,而不是Connections(1)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-02-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多