简体   繁体   English

VBA If/Then 基于记录计数

[英]VBA If/Then based on Record Count

I'd like to create an If/Then statement in VBA where if there are multiple records in the recordset one message populates, and if there is only record another message populates.我想在 VBA 中创建一个 If/Then 语句,如果记录集中有多个记录,一条消息将填充,如果只有一条记录,则另一条消息将填充。

Right now I'm using现在我正在使用

If rst.EOF = False Then...

Else ...

End If

This is only returning the first condition regardless of how many records are in the recordset though.这只是返回第一个条件,不管记录集中有多少记录。

Is there something else I'm missing?还有什么我想念的吗?

You are missing to count the records:你缺少统计记录:

If rst.EOF = False Then
    rst.MoveLast
    rst.MoveFirst
    If rst.RecordCount = 1 Then
        ' One record.
    Else
        ' More records.
    End If
Else
    ' No records.
End If

Depending on the size of your recordset, .MoveLast can severely impact on performance and since .RecordCount will not yield the total number of records, but rather the number of accessed records, a call to .MoveLast is required.根据记录集的大小, .MoveLast可能会对性能产生严重影响,并且由于.RecordCount不会产生记录总数,而是产生访问记录的数量,因此需要调用.MoveLast

To offer an alternative, consider the following:要提供替代方案,请考虑以下因素:

If rst.EOF Then
    ' No records
Else
    rst.MoveFirst
    rst.MoveNext
    If rst.EOF Then
        ' 1 record
    Else
        ' More than 1 record
    End If
End If

This first tests whether the recordset is already at .EOF , and if so, there are no records in the recordset.这首先测试记录集是否已经在.EOF ,如果是,则记录集中没有记录。

If we have some records, it moves the cursor to the first record ( .MoveFirst ), and then to the next record ( .MoveNext ) if it exists.如果我们有一些记录,它会将光标移动到第一条记录 ( .MoveFirst ),然后移动到下一条记录 ( .MoveNext )(如果存在)。

If we have now reached .EOF , there must be only one record in the recordset;如果我们现在到达.EOF ,则记录集中必须只有一条记录; else, there are more records.否则,还有更多记录。

Since you only need to branch for the case there is a single record, this method means you are accessing the minimum number of records to determine this condition.由于您只需要为只有一条记录的情况进行分支,因此此方法意味着您正在访问最少数量的记录来确定此条件。

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

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