简体   繁体   English

SQL记录计数VBA ADODB连接

[英]SQL Record Count VBA ADODB connection

Trying to work a RecordSet count in VBA Using ADODB recordset but it won't seem to get the count to work properly. 尝试使用ADODB记录集在VBA中处理RecordSet计数,但似乎无法使该计数正常工作。

I've got 50 records in a worksheet with unique ID's, some of them are already in a database and some are not, the code itself is to loop through each cell and get the value of the cell and run that through an SQL select statement if theres a hit then say found if not then say nothing. 我在工作表中有50条具有唯一ID的记录,其中一些已经在数据库中,而有些则没有,代码本身就是循环遍历每个单元格并获取该单元格的值并通过SQL select语句运行如果有成功,则说找到,否则就什么也不说。

Unfortunately it seems to return the same result for everything, even the id's i know do not exist. 不幸的是,它似乎为所有内容返回相同的结果,即使我知道ID都不存在。

Code bellow 波纹管

Sub NO6_ChequeCheck()

Dim con As ADODB.Connection
Dim rec As ADODB.Recordset

Set con = New ADODB.Connection
Set rec = New ADODB.Recordset


Dim sql As String
Dim client As String

Dim myRange As Range
Dim myCell As Range

Set myRange = Range("A2:A52")

Dim i As Integer
i = 2

With con
    .Provider = "MSDASQL"
    .ConnectionString = "DSN=localhostTest"
    .Open
End With

For Each myCell In myRange

    client = myCell.text

    sql = "SELECT * FROM crm_client_cheques WHERE id = '" & client & "' "

    rec.Open sql, con

    If rec.RecordCount = 0 Then
        Cells(i, "H").Value = "Nothing"
    Else
        Cells(i, "H").Value = "Found"
    End If

    rec.Close

    i = i + 1

Next myCell

The main thing I've come across is that if i toggle that 0 to say 50 and mess with the = sign and change it to < or > then the results will change to either , which leads me to believe its not resetting the recordcount back so it just stacks each time so its always going up each loop and not going back to 0. 我遇到的主要问题是,如果我将0切换为50,然后将=符号弄乱,然后将其更改为<或>,则结果将更改为其中一个,这使我相信它不会将Recordcount重置为零因此它每次都会堆叠,因此它总是在每个循环中向上而不是返回0。

i have tried telling it to close and equal nothing and moved various bits of code around but nothing helps much. 我试图告诉它关闭并等于零,并四处移动各种代码,但无济于事。

All help appriciated 所有帮助

You need to check whether there are any records returned by your sql query. 您需要检查sql查询是否返回任何记录。 You can do that by 你可以这样做

 If Not (rec.BOF And rec.EOF) Then 'There are no records
      Cells(i, "H").Value = "Nothing"
 else
      Cells(i, "H").Value = "Found"
 End if

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

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