【问题标题】:How to access a query with a dependant range of cells如何访问具有相关单元格范围的查询
【发布时间】:2013-05-09 20:54:39
【问题描述】:

此函数打开与 sql 数据库的连接,收集数据并将其带回并将其复制到单元格 O6 及以后。我遇到了两个问题。我的第一个是我想选择要查询的单元格范围。范围从 I6 开始,进入单元格 I“lastrow”,最后一个单元格包含我要查询的数据。

  1. 我不知道在我的查询中说什么:

    where s.cusip = ""
    

和 2. 它告诉我有一个未定义的用户定义类型。

非常感谢任何帮助

Private Sub CommandButton1_Click()

Call datacollect_alternate ' my code

End Sub

Public Sub datacollect_alternate()

 Dim rs As New ADODB.Recordset
 Dim cmd As New ADODB.Command
 Dim i_date As String
 cmd.ActiveConnection = OpenConnectionDPDMView

 cmd.CommandText = "select s.description, s.rate coupon, sa.rrb_factor from dpdm.security s left join dpdm.security_analytics sa on s.security_id = sa.security_id where s.cusip= '" & Range("i6").Value & "' And sa.as_of_date = trunc(sysdate)"
 Set rs = cmd.Execute
'Declare variables'
Dim Lastrow As Integer
'Lastrow = Cells(Cells.rows.Count, "C").End(xlUp).Row
Lastrow = Range("c65336").End(xlUp).Row

'Copy Data to Excel'
    ActiveSheet.Range("O6").CopyFromRecordset rs

copy_cells (Lastrow)

End Sub

【问题讨论】:

    标签: sql excel connection vba


    【解决方案1】:

    对于你的 WHERE 子句,你可以尝试这样的事情:

    dim sWhereClause as string
    dim iRow as integer
    
    sWhereClause = "where s.cusip IN ('"
    
    for irow=6 to LastRow
        sWhereClause =sWhereClause & range("I" & irow).text & "','"      
    next
    
    debug.print sWhereClause ' output to Immediate window
    
    sWhereClause =left(sWhereClause ,len(sWhereClause)-2) ' to remove the last comma and quote
    sWhereClause =    sWhereClause & ")" ' close the IN bracket
    

    所以将字符串 sWhereClause 附加到您的 SQL 查询中并开始调试!

    你在哪一行得到错误?

    【讨论】:

    • 我编辑了问题中的代码,我在查询中发现了问题,所以它现在可以工作,但这仅适用于一行,我会使用你的建议,看看我是否可以让它工作,
    【解决方案2】:
    Public Sub datacollect_alternate()
    
     Dim rs As New ADODB.Recordset
     Dim cmd As New ADODB.Command
     Dim i_date As String
     Dim Lastrow As Integer
     Dim sWhereClause As String
     Dim iRow As Integer
    
     Lastrow = Range("I65336").End(xlUp).Row
     cmd.ActiveConnection = OpenConnectionDPDMView
    
    
     For iRow = 6 To Lastrow
         sWhereClause = "where s.cusip= '"
         sWhereClause = sWhereClause & Range("I" & iRow).Value
    
         cmd.CommandText = "select s.description, s.rate coupon, sa.rrb_factor from dpdm.security s left join dpdm.security_analytics sa on s.security_id = sa.security_id " & sWhereClause & "' And sa.as_of_date = trunc(sysdate)"
         Set rs = cmd.Execute
    
        'Copy Data to Excel'
        ActiveSheet.Range("O" & iRow).CopyFromRecordset rs
    
     Next
    
    
    
     copy_cells (Lastrow)
    
    End Sub
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-07-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多