【问题标题】:Why can I run a Query via the query editor but running through vba fails?为什么我可以通过查询编辑器运行查询但通过 vba 运行失败?
【发布时间】:2017-10-05 04:13:58
【问题描述】:

我正在尝试从使用 VBA 访问的表中检索记录。到目前为止,我有这个简单的功能:

Private Function GNCN() As String

Dim cn As New ADODB.Connection
Dim rs As New ADODB.Recordset
Dim cm As ADODB.Command
Dim strSQL As String
Dim intYD As Integer

Set cn = CurrentProject.Connection
'cn.CursorLocation = adUseClient
rs.CursorLocation = adUseClient
rs.LockType = adLockReadOnly

intYD = 16

strSQL = "SELECT DCN FROM tblDCD WHERE (DCN like '" & intYD & "*')"
Set rs = cn.Execute(strSQL)

Debug.Print rs.RecordCount

Set rs = Nothing
Set cm = Nothing
Set cn = Nothing

End Function

当我运行它时,我没有返回任何记录。

但是,如果我使用 SQL 查询:

SELECT DCN FROM tblDCD WHERE (DCN like '16*')

并在 Access 的查询生成器中运行它,我得到大约 912 条记录返回,所以我知道我能够检索记录并且查询本身似乎是正确的。

该表是由字符串值组成的简单数据,例如(在 DCN 列中):

"13000"
"17001"
"16003"

总共大约 38000,所以我不会在这里全部打印出来......

有谁知道为什么这将通过查询生成器而不是通过 VBA 工作?

谢谢

【问题讨论】:

    标签: ms-access vba


    【解决方案1】:

    似乎混合了 DAO 和 ADODB。考虑:

    Private Function GNCN() As String
    
    Dim rs As DAO.Recordset
    Dim strSQL As String
    Dim intYD As Integer
    
    intYD = 13
    
    strSQL = "SELECT DCN FROM Rates WHERE DCN like '" & intYD & "*';"
    Set rs = CurrentDb.OpenRecordset(strSQL)
    rs.MoveLast
    Debug.Print rs.RecordCount
    
    Set rs = Nothing
    
    End Function
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-11-12
      • 2012-01-25
      • 2012-07-05
      • 2017-10-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多