DLookUp select 辅助电子邮件,如果主电子邮件为空或为空

DLookUp select secondary email if primary is empty or null

我有一个表格,可以select根据保险过期的公司发送电子邮件。一些公司同时拥有商务和个人电子邮件,而其他公司则拥有其中之一。 我正在使用 DLookUp 函数 select 基于满足过滤条件的供应商的电子邮件。 有没有一种方法可以让我 select BusinessEmail,但如果他们没有,我会 select 使用 PersonalEmail 代替?

目前我从 =DLookUp("BusinessEmail","tblContacts","Supplier ID = " & [txtSupplierID] 开始,然后在其中使用 IIf 语句,但我不知道它会如何 select 另一封电子邮件,或者它是否会那样工作.

contacts sample data

如果找不到值,DLookup() 函数 returns null,因此您可以使用 Nz() 函数检查个人电子邮件,如果是企业电子邮件为空。

由于我们将 return 值分配给一个字符串并且字符串不能包含空值,我们再次使用 Nz() 函数来 return 一个空字符串,如果个人电子邮件也不存在(以避免错误)。

Dim criteria As String
criteria = "[Supplier ID] = " & [txtSupplierID]

Dim email As String
email = Nz(DLookup("BusinessEmail", "tblContacts", criteria), Nz(DLookup("PersonalEmail", "tblContacts", criteria), vbNullString))

编辑:


DLookup 添加第二条规则以排除空值,应该可行。查看帮助函数以通过输出参数获取电子邮件并报告 success/failure:

Private Function TryGetEmail(ByVal supplierId As Long, ByRef outEmail As String) As Boolean

    Dim retValue As Variant
    
    'try to get business
    retValue = DLookup("BusinessEmail", "tblContacts", "[Supplier ID] = " & supplierId & " AND BusinessEmail Is Not Null")
    If Not IsNull(retValue) Then
        outEmail = retValue
        TryGetEmail = True
        Exit Function
    End If
    
    'try to get personal
    retValue = DLookup("PersonalEmail", "tblContacts", "[Supplier ID] = " & supplierId & " AND PersonalEmail Is Not Null")
    If Not IsNull(retValue) Then
        outEmail = retValue
        TryGetEmail = True
        Exit Function
    End If
    
    'none found
    outEmail = vbNullString
    TryGetEmail = False
    
End Function

调用它:

Sub T()

    Dim supplierId As Long
    Dim email As String
    
    supplierId = 19
    
    If Not TryGetEmail(supplierId, email) Then
        MsgBox "No email found"
        Exit Sub
    End If
    
    'email now holds one of the two emails

End Sub

首先,将“Supplier ID”字段修改为“SupplierID”,这将使您的开发更容易。

下面是一些同时使用 Dlookup 和 IIf 的代码,将结果放在名为 txtEmail 的文本框中:

Private Sub getEmail()
    txtEmail = DLookup("Iif(Isnull(BusinessEmail),PersonalEmail,BusinessEmail)", "tblContacts", "SupplierID = " & txtSupplierID)
End Sub

或者这个:

Private Sub getEmail()
    Dim Email As Variant
    
    Email = DLookup("BusinessEmail", "tblContacts", "SupplierID = " & txtSupplierID)
    If IsNull(Email) Then Email = DLookup("PersonalEmail", "tblContacts", "SupplierID = " & txtSupplierID)
    
    txtEmail = Email
End Function