1

此函数打开与 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
4

2 回答 2

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

你在哪一行得到错误?

于 2013-05-09T21:56:25.183 回答
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
于 2013-05-10T13:11:36.750 回答