此函数打开与sql数据库的连接,收集数据并将其恢复并将其复制到单元格O6及以后。我遇到了两个问题。我的第一个是想要选择要查询的单元格范围。范围从I6开始,然后转到单元格I“lastrow”,其中包含我要查询的数据的最后一个单元格。
我不知道在我的查询中该说些什么:
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
答案 0 :(得分: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查询并开始调试!
您收到错误的是哪一行?
答案 1 :(得分:0)
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