如果数组中存在值,则打印记录集

时间:2014-06-11 15:54:16

标签: arrays excel-vba ado vba excel

vb的新手,如果变量等于我的数组中的值,我正在努力从记录集返回数据。

我认为到目前为止我所做的是正确的,但最后一点有问题。我需要编写一些内容来说“如果范围内的值等于我的数组中的值,则打印记录集”。

我希望有人可以提供帮助。我也是vb的新手,所以关于如何改进我的代码的任何建议都会很棒。提前致谢!!布赖恩

        Sub FindCardOrdersv2()

        ' Initialize variables.
        Dim cn As ADODB.Connection
        Dim rs As New ADODB.Recordset
        Dim provStr As String
        Dim intMaxCol As Integer
        Dim intMaxRow As Integer
        Dim rsFilter As Range
        Dim i As Integer
        Dim rng As Variant
        Dim payid(1 To 10) As String
        Dim tw As ThisWorkbook

        Workbooks("cleanse.xlsm").Activate
        Worksheets("Sheet1").Activate

        ' Create new instances
        Set cn = New ADODB.Connection
        Set rs = New ADODB.Recordset


        ' sql query
        sql = "SELECT TOP 100 t.tri_transactionidcode," _
              & "SUBSTRING(t.tri_reference, 1, 9) AS merchantref," _
              & "t.tri_additionalreferencenumber, t.CreatedOn, t.tri_amount, ISNULL(t.tri_paymenttransactiontypeidName, 'Online')" _
              & " FROM dbo.tri_onlinepayment t INNER JOIN dbo.tri_transaction tr ON tr.tri_onlinepaymentid = t.tri_onlinepaymentId" _
              & " WHERE t.tri_transactionresult = 9"

        ' Specify the OLE DB provider.
        cn.Provider = "sqloledb"

        ' Specify connection string on Open method.
        cn.Open "Data Source=IFL-SQL11;Database=IFL_MSCRM;Trusted_Connection=yes;Integrated Security=SSPI"



        ' Assign active connection to recordset
        Set rs.ActiveConnection = cn
        'intMaxCol = rs.Fields.Count

        ' Define cursors and open sql
        With rs
            .CursorLocation = adUseClient
            .CursorType = adOpenStatic
            .LockType = adLockReadOnly
            .Open sql
        End With

        For i = 1 To 3
            payid(i) = rs.Fields.Item(0)
            Debug.Print rs(0)
            Debug.Print rs(1)
            Debug.Print rs(3)
            rs.MoveNext
        Next i

        'rsFilter = Range("A1:A10")



        For Each rsFilter In Range("A1:A10").Cells
            If rsFilter.Value = payid Then
            Debug.Print rs(1)
            rs.MoveNext
            End If
        Next

        'If rs.RecordCount > 0 Then
        '   With Worksheets("Sheet1")
        '   .Range("B1:B2").CopyFromRecordset rs
        '   End With
        'End If


        rs.Close
        cn.Close

        Set rs = Nothing
        Set cn = Nothing
        End Sub

1 个答案:

答案 0 :(得分:0)

在内部添加一个额外的for循环,以将范围中的每个值与数组值进行比较

For Each rsFilter In Range("A1:A10").Cells
   For i=1 To 3
      If rsFilter.Value = payid(i) Then
        Debug.Print rs(1)
        rs.MoveNext
      End If   
   Next i    
Next