简体   繁体   English

VBA中的MS Access 2016 SQL

[英]MS Access 2016 SQL in VBA

I'm sure I'm making a simple mistake. 我确定我犯了一个简单的错误。 I have a SQL Server with tables that I have linked in MS Access. 我有一个SQL Server,其中包含已在MS Access中链接的表。 I am trying to run a SQL query in Form OnLoad to populate a text box based on a value in my form. 我正在尝试在Form OnLoad运行SQL查询,以基于表单中的值填充文本框。

Below is my code. 下面是我的代码。 The field I want returned TE is varchar in MSSQL and short text in Access. 我要返回的TE字段是MSSQL中的varchar和Access中的短文本。 I am getting a 'Type Mismatch' on the textbox. 我在文本框上看到'Type Mismatch' When I try outputting to a MsgBox I get: 当我尝试输出到MsgBox我得到:

'rst!TE not in collection'. “ rst!TE未收集”。

TN and TN_1 are smallint, in Access they are Number. TN和TN_1是smallint,在Access中它们是Number。

Dim rst As DAO.Database
Set rst = CurrentDb

rst.OpenRecordset "SELECT dbo_STCH.TE FROM dbo_STCH RIGHT JOIN dbo_SCVR ON               dbo_STCH.TN = dbo_SCVR.TN_1 WHERE dbo_SCVR.TN_1=99;"

Me.Text22.Text = rst!TE
rst.Close
Set rst = Nothing

You are conflating DAO recordsets and databases and hence the message is correct as the item is not found in collection. 您正在混合DAO记录集和数据库,因此该消息是正确的,因为在集合中找不到该项目。 Simply initialize rst as a recordset and assign it to OpenRecordset call. 只需将rst初始化为记录集,并将其分配给OpenRecordset调用即可。

Dim rst As DAO.Recordset

Set rst = CurrentDb.OpenRecordset("SELECT dbo_STCH.TE FROM dbo_STCH" _
                                  & " RIGHT JOIN dbo_SCVR ON dbo_STCH.TN = dbo_SCVR.TN_1" _
                                  & " WHERE dbo_SCVR.TN_1=99;")

Me.Text22.Text = rst!TE

rst.Close
Set rst = Nothing

You have to use rst.MoveFirst to move to the first record of the opened recordset before reading any values from it. 您必须使用rst.MoveFirst移至打开的记录集的第一条记录,然后再从中读取任何值。

Also as the answer above you have to Set rst = CurrentDb.OpenRecordset 同样作为上述答案,您必须Set rst = CurrentDb.OpenRecordset

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

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