1

我一直在网上搜索如何使用 VBA 和 SQL 在 Access 中运行查询并想出这个。一般的想法是,从组合框中选择的值应该运行基于 ID Selected 的查询,例如。用户选择公司表中 ID 为 5 的公司。然后用相关数据填充下面的文本框。我还有另一个包含员工数据的表,其中与使用 CompanyID 作为主键的公司表有关系,如果员工公司 id = 5,他们在这种情况下为 asda 工作。出于某种原因,在运行此查询时,我收到一条错误消息,指出可能存在评估函数的错误

Public Function DataLookup()
Dim CompDetailSQL As String
Dim rst As DAO.Recordset
Dim CompID As String
CompID = Me.lstBoxCompanyName.Value
CompDetailSQL = "SELECT Companies.CompanyID, Companies.CompanyName,       Companies.AddressNo, Companies.AddressLine1, Companies.AddressLine2, Companies.AddressLine3, Companies.AddressPostcode, Companies.AddressCounty, Link_Table.FirstName, Link_Table.LastName FROM Companies INNER JOIN Link_Table ON Companies.CompanyID = Link_Table.CompanyID WHERE " = CompID
Set rst = CurrentDb.OpenRecordset(CompDetailSQL, dbOpenSnapshot)
Me.lblAddressLine1.Value = rst!Companies.AddressLine1
Me.lblAddressLine2.Value = rst!Companies.AddressLine2
Me.lblAddressLine3.Value = rst!Companies.AddressLine3
Me.lblAddressPostcode.Value = rst!Companies.AddressPostcode
Me.lblAddressCounty.Value = rst!Companies.AddressCounty
rst.Close
Set rst = Nothing
End Function
4

2 回答 2

2

你这里可能有问题...

CompDetailSQL = "SELECT ... WHERE " = CompID

无论它是否引发错误,我都怀疑该WHERE子句不会满足您的需求。

给自己一个机会来检查您的代码创建的完整 SQL 语句。在后面加上这一行CompDetailSQL = ...

Debug.Print CompDetailSQL 

之后,运行代码并转到即时窗口 ( Ctrl+ g) 以查看输出。您可以复制语句文本,然后将其粘贴到新 Access 查询的 SQL 视图中以进行测试。

当您有所需的查询时,然后按字段名称引用记录集字段......不符合源表的名称。

'rst!Companies.AddressLine1
rst!AddressLine1

你说填充文本框。如果lblAddressLine1真的是一个文本框,这应该工作......

Me.lblAddressLine1.Value = rst!AddressLine1

但是,如果lblAddressLine1实际上是一个标签控件,则设置其.Caption而不是.Value属性。

Me.lblAddressLine1.Caption = rst!AddressLine1
于 2013-09-23T17:02:59.550 回答
1

干杯家伙问题解决了。SQL 查询本身不会在访问查询设计下运行。

CompDetailSQL = "SELECT Companies.CompanyID, 
Companies.CompanyName, 
Companies.AddressNo, 
Companies.AddressLine1, 
Companies.AddressLine2, 
Companies.AddressLine3, 
Companies.AddressPostcode, 
Companies.AddressCounty,
Link_Table.FirstName, 
Link_Table.LastName
FROM Companies 
INNER JOIN 
Link_Table ON Companies.CompanyID = Link_Table.CompanyID 
WHERE Companies.CompanyID = " & Me.lstBoxCompanyName.Value

但是上面的查询确实有效,似乎我错过了Companies.CompanyID问题已解决,现在产生了一个新问题。但一个完全不同的问题。谢谢你的帮助@hansUp @bamie9l

于 2013-09-24T14:02:33.313 回答