在2个雇用日期VBA和SQL之间提取员工

时间:2015-06-02 06:16:14

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

我设计了一个宏,它应该从工作簿数据库中提取所有在2个日期之间雇用的员工。

Unfortunatley我在运行查询时收到错误消息。

错误: 标准表达式中的数据类型不匹配。

我不知道如何解决这个问题。

我的区域设置:

短日期:dd.MM.yyyy 长日期:dddd,d.MMMM.yyyy 一周的第一天:星期一

这里是代码:

Public Sub HIREDATE()
Application.ScreenUpdating = False

Dim cnStr As String
Dim rs As ADODB.Recordset
Dim query As String
Dim fileName As String
Dim pom1 As String
Dim x As String, w, e, blad As String, opis As String
Set w = Application.FileDialog(msoFileDialogFilePicker)
With w
.AllowMultiSelect = False

    If .Show = -1 Then
    fileName = w.SelectedItems(1)
    Else
    Exit Sub
    End If

End With

    cnStr = "Provider=Microsoft.ACE.OLEDB.12.0;" & _
               "Data Source=" & fileName & ";" & _
               "Extended Properties=Excel 12.0"

On Error GoTo Anuluj
x = InputBox("Wprowadz dwie daty od do oddzielając je przecinkiem -- Przykład 01.01.2015,01.05.2015")



       strg = ""

       k = Split(x, ",")
                e = Application.CountA(k)
        For m = LBound(k) To UBound(k)

            If e = 1 Then
            strg = strg & " [DEU1$].[Last Start Date] = '" & k(m) & "';"
            Exit For
            ElseIf e = 2 And e Mod 2 = 0 Then
            strg = " [DEU1$].[Last Start Date] BETWEEN '" & CDate(k(m)) & "' AND '" & CDate(k(m + 1)) & "';"
            Exit For
            End If

        Next m

On Error GoTo opiszblad

    Set rs = New ADODB.Recordset

query = "SELECT [Emplid], [First Name]+ ' ' +[Last Name] From [DEU1$] WHERE" & strg

    rs.Open query, cnStr, adOpenUnspecified, adLockUnspecified

    Cells.Clear

Dim cell As Range, i As Long

    With Range("A3").CurrentRegion
    .Select
        For i = 0 To rs.Fields.Count - 1
            .Cells(1, i + 1).Value = rs.Fields(i).Name
        Next i


    Range("A4").CopyFromRecordset rs
    .Cells.Select

    .EntireColumn.AutoFit
    End With

    rs.Close
Application.ScreenUpdating = True

Exit Sub

Anuluj:

Exit Sub

opiszblad:
e = Err.Number
blad = Err.Source
opis = Err.Description
opisbledu = MsgBox(e & " " & blad & " " & opis, vbInformation, "Błąd")
Exit Sub
End Sub

1 个答案:

答案 0 :(得分:1)

您需要为日期设置格式正确的字符串表达式并验证用户输入:

If e = 1 And IsDate(k(m)) Then
    strg = strg & " [DEU1$].[Last Start Date] = #" & Format(DateValue(k(m)), "yyyy\/mm\/dd") & "#;"
    Exit For
ElseIf e = 2 And e Mod 2 = 0 And IsDate(k(m + 1)) Then
    strg = " [DEU1$].[Last Start Date] BETWEEN #" & Format(DateValue(k(m)), "yyyy\/mm\/dd") & "# AND #" & Format(DateValue(k(m + 1)), "yyyy\/mm\/dd") & "#;"
    Exit For
End If