繁体   English   中英

如何访问具有相关单元格范围的查询

[英]How to access a query with a dependant range of cells

此函数打开与sql数据库的连接,收集数据并将其带回并复制到单元格O6中。 我遇到了两个问题。 我首先要选择要查询的单元格范围。 范围从I6开始,然后转到单元格“ 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

对于您的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查询中并开始调试!

您在哪一行出现错误?

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM