为什么我的ADO Access连接提供的结果与Access应用程序中运行的相同查询不同?

时间:2015-10-23 20:27:41

标签: excel vba excel-vba ms-access access-vba

我一直试图解决这个问题超过一天,我觉得答案归结为Access如何处理数据类型,但我仍然没有想到它。我已经简化了这个问题,希望它更容易解决。我在Excel工作簿中有2列 - 列A是文本,列B是日期。基本上我只想在列A不为空时从列B中选择日期。这在理论上运作良好,但不适用于我遇到的实际情况。

Ex:而不是B列是所有日期,B列的其中一个值只是一个空字符串。为了解决这个问题,我简单地添加了一个IIF语句,如果列B为='',则将其设为0:

querystr = "Select IIF([Enroll Date] = '',0,[Enroll Date]) As vdate FROM [Sheet1$] where [Account Number] IS NOT NULL"

当我将工作表导入Access时,此查询工作正常,但当我将其与Excel VBA的ADO连接一起使用时,所有记录都返回Empty,除了返回的零长度字符串空值。这个子将为您设置整个工作簿并演示整个工作:

Sub flow()

Dim con As Object
Dim rec As Object
Dim path As String
Dim y As Integer: y = 1
Dim sht1 As Worksheet

Set sht1 = ActiveSheet

path = SetData()

Set con = CreateObject("ADODB.Connection")
Set rec = CreateObject("ADODB.Recordset")

con.ConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" & path & ";" & _
                            "Extended Properties=" & Chr(34) & "Excel 12.0 Xml;HDR=YES" & Chr(34) & ";"


con.Open

    querystr = "Select IIF([Enroll Date] = '',0,[Enroll Date]) As vdate FROM [Sheet1$] where [Account Number] IS NOT NULL"

rec.Open querystr, con

Range("D2").CopyFromRecordset rec
'every record is blank
rec.Close
rec.Open querystr, con

Do Until rec.EOF
    y = y + 1
    If IsEmpty(rec.Fields("vdate")) Then
        Range("G" & y).Value = "Empty"
    ElseIf IsNull(rec.Fields("vdate")) Then
        Range("G" & y).Value = "Null"
    End If
    rec.movenext
Loop

End Sub

Function SetData() As String

Dim sht1 As Worksheet: Set sht1 = ThisWorkbook.Sheets(1)

    With sht1
        .Columns.Item("A").NumberFormat = "@"
        .Columns.Item("B").NumberFormat = "m/d/yyyy"
        .Range("A1").Value = "Account Number"
        .Range("B1").Value = "Enroll Date"
        .Columns("A:B").AutoFit
        For x = 1 To 5
            .Range("A" & x + 1).Value = x
        Next x
        Union(.Range("B2:B4"), .Range("B6")).Value = DateSerial(2016, 4, 1)
        'change B5 to accounting format
        .Range("B5").NumberFormat = "_($* #,##0.00_);_($* (#,##0.00);_($* ""-""??_);_(@_)"
        .Range("B5").Value = vbNullString
    End With


    With ThisWorkbook
        .Save
        SetData = .FullName
    End With

End Function

1 个答案:

答案 0 :(得分:2)

[Enroll Date] = ''声明中将IsNull([Enroll Date])更改为IIF

在这种情况下,我怀疑[Enroll Date]在Access中格式化为Date,而Date数据类型的值不能为''(或空字符串)。它可以是有效日期,也可以是null。

也就是说,在Access和Excel之间传输数据时,您必须在每个系统中获取数据类型,以使其正常工作。我不能在这里给你一个不错的解释,但是如果你谷歌的话,你可以在将数据从Excel传输到Access时找到很多讨论数据类型问题的事情。