0

This seems like it should be a relatively straightforward task but I've tackled it a few different ways with no luck so far.

I have two tables : People and Addresses. I have a form with a recordsource that is a query joining these two tables. What I want to do is have the header display "The database currently contains [txtPersonCount] people at [txtAddressCount] addresses."

Since person key and address key are distinct within their respective tables my first thought was simply to set the controlsource of the textboxes to =Count([tblPeople].[PersonID]) and =Count([tblAddress].[AddressID]).

Oddly, the count of address ID appears in both textboxes with this method. I assume what's happening is rather than counting the IDs from the respective tables, the IDs are being counted from the query behind the form's recordsource (for which there are more addresses than people, so it would make sense).

I then attempted to basically do the same thing by declaring my SQL queries as a string :

Dim sql As String
sql = "SELECT COUNT(tblPeople.[PersonID]) FROM tblPeople;"

Forms![frmBrowse].[txtPersonCount].ControlSource = sql

But that only ends up making the textbox display the text of the query. Changing the string to be "=SELECT COUNT...." makes no difference.

Any ideas on how to solve this?

4

3 回答 3

1

您已经创建了 SQL 字符串,但在执行它或将其绑定到记录集之前,您将无法使用结果。

'Create a connection to your database
Dim db As DAO.Database
Set db = CurrentDb()

'Create a record set that will let you access values from your query
Dim rs As DAO.Recordset
Set rs = db.OpenRecordset("SELECT COUNT(tblPeople.[PersonID]) as NumOfPeople FROM tblPeople;")

'You don't want to change the control source because that is the property of where the value will be stored.  You want to change the value of the text box.
Forms![frmReports].[Text144] = rs!NumOfPeople

'Close the connection and recordset
rs.Close
db.Close
Set rs = Nothing
Set db = Nothing
于 2013-06-12T15:49:10.837 回答
1

我会简单地在 People 表 和Adresses 表上使用一个DCount("*","People")函数。在我看来,这比尝试在 JOIN 上进行 DISTINCT COUNT 更快、更明智。 如果你真的想要一个 DISTINCT COUNT,你将不得不使用一个棘手的交叉表查询。 我在这里发布了一些东西(法语),Roger 的 Access 博客比较了 4 种方法来做到这一点
DCount("*","Addresses")

于 2013-06-12T15:49:25.043 回答
0

这是一个链接,它根据Select语句中的参数循环遍历选定的记录。它使用 .RecordCount 关闭记录集,但关键是必须首先访问记录(因此循环)。

于 2013-06-12T15:44:42.610 回答