如何在Word VBA SQL查询中处理空值?

时间:2010-10-20 22:25:58

标签: sql vba ms-word

我有一个下拉列表绑定到Excel电子表格中的列。我在下拉列表中选择了一个客户,然后从excel电子表格中填充了一些包含相关数据的地址字段。

代码:

Private Sub cboCompany_Change()
            Dim customerName As String
            customerName = cboCompany.Value
            customerName = Replace(customerName, "'", "''")

            Dim i As Integer
            Dim cn As ADODB.Connection
            Dim rsT As New ADODB.Recordset

            Dim customer As String
            Dim postcode As String
            Dim address1 As String
            Dim suburb As String
            Dim addressType As String
            Dim state As String
            Dim country As String


            Set cn = New ADODB.Connection
            With cn
            .Provider = "Microsoft.Jet.OLEDB.4.0"
            .ConnectionString = "Data Source=C:\Customer.xls;Extended Properties=Excel 8.0;"
            .CursorLocation = adUseClient
            .Open
            End With
            rsT.Open "SELECT Customer, Postcode, [Address 1] AS Address1, [Postal Suburb] AS Suburb, [Address Type] AS AddressType, State, Country FROM Customers WHERE [Address Type] = 'Postal Address' AND Customer = '" & customerName & "'", cn, adOpenStatic

            i = 0

            With rsT
            Do Until .EOF
            customer = rsT.Fields("Customer")
            postcode = rsT.Fields("Postcode")
            address1 = rsT.Fields("Address1")
            suburb = rsT.Fields("Suburb")
            addressType = rsT.Fields("AddressType")
            state = rsT.Fields("State")
            country = rsT.Fields("Country")

            CompanyAddress1.Value = address1
            CompanyAddress2.Value = suburb + " " + state + " " + postcode + " " + country
            CompanyName.Value = customer
            .MoveNext
            i = i + 1
            Loop
            End With
End Sub

但是,如果其中一个字段(例如郊区)为空,则表单崩溃,我该如何处理?

1 个答案:

答案 0 :(得分:0)

您可以使用vba函数 IsNull 。如下所示

If IsNull(rsT.Fields("Customer")) Then

End If

or 

If Not IsNull(rsT.Fields("Customer")) Then

End If

享受!