访问VBA查询

时间:2013-09-23 16:54:53

标签: sql vba ms-access access-vba

我一直在网上搜索如何使用VBA& amp ;;在Access中运行查询SQL并想出这个。一般的想法是,从组合框中选择的值应该基于所选的ID运行查询。用户在公司表中选择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

2 个答案:

答案 0 :(得分: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

答案 1 :(得分: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