簡體   English   中英

使用visual basic導出excel到sql

[英]export excel to sql using visual basic

希望有人可以幫我編寫這個腳本

我正在嘗試使用附加到按鈕的宏創建一個excel文件,該按鈕將數據導出到sql。 我的sql表如下

    RecordedPeriod (datetime, not null)

    EventDate (varchar(8), not null)

    ID (int, not null)

    DeptCode (varchar(2), not null)

    OpCode (varchar(2), not null)

    StartTime (time(0), not null)

    FinishTime (time(0), not null)

    Units (int, not null)

在Visual Basic for Applications中創建宏時,我的代碼如下

Sub Button1_Click()

Dim conn As New ADODB.Connection
Dim iRowNo As Integer
Dim sRecordedPeriod, sEventDate, sID, sDeptCode, sOpCode, sStartTime, sFinishTime, sUnits  As String

With Sheets("Sheet1")

    'Open a connection to SQL Server
    conn.Open "Provider=SQLOLEDB;Data Source=db1\db1;Initial Catalog=ProdTrack;Integrated Security=SSPI;"

    'Skip the header row
    iRowNo = 2

    'Loop until empty cell in FirstName
    Do Until .Cells(iRowNo, 1) = ""
        sRecordedPeriod = .Cells(iRowNo, 1)
        sEventDate = .Cells(iRowNo, 2)
        sID = .Cells(iRowNo, 3)
        sDeptCode = .Cells(iRowNo, 4)
        sOpCode = .Cells(iRowNo, 5)
        sStartTime = .Cells(iRowNo, 6)
        sFinishTime = .Cells(iRowNo, 7)
        sUnits = .Cells(iRowNo, 8)

        'Generate and execute sql statement to import the excel rows to SQL Server table
        conn.Execute "insert into dbo.TimeLog (RecordedPeriod, EventDate, ID, DeptCode, Opcode, StartTime, FinishTime, Units) values ('" & sRecordedPeriod & "', '" & sEventDate & "', '" & sID & "', '" & sDeptCode & "', '" & sOpCode & "', '" & sStartTime & "', '" & sFinishTime & "', '" & sUnits & "')"

        iRowNo = iRowNo + 1
    Loop

    MsgBox "Data Successfully Exported."

    conn.Close
    Set conn = Nothing

導出時收到此錯誤消息。

    Run-time error '2147217913 (80040e07)':

    Conversion failed when converting date and/or time from character string.

有沒有人有什么建議?

這就是我的excel表的外觀。 我試圖改變時間格式仍然出錯。 我的EventDate是SQL中的Varchar所以那里應該沒有問題。

    RecordedPeriod  EventDate   ID  DeptCode    OpCode  StartTime   FinishTime  Units
    NULL           6/15/2017 45318   DS         DS      8:00:00     9:00:00     500
    NULL           6/15/2017 45318   DS         DS      9:00:00     9:15:00     500
    NULL           6/15/2017 45318   DS         DS      9:15:00     9:20:00     500

導出到sql后,我的excel文件中的數據被刪除,我們將每天丟棄新數據。

您在查詢中提供的日期格式不正確。 以下是可接受格式的列表,您需要確保使用的格式符合以下條件:

https://docs.microsoft.com/en-us/sql/t-sql/data-types/date-transact-sql

我建議使用Debug.Print "insert int..."並檢查immediates窗口中的格式(在VBExplorer中),然后運行查詢

在您的設計中考慮導出到XML並使用XSLT(或DTD等)創建規則以供SQL導入。 XML可以是在格式之間傳遞數據的強大方式。

添加: https//docs.microsoft.com/en-us/sql/relational-databases/import-export/examples-of-bulk-import-and-export-of-xml-documents-sql-server

隨着數據庫和電子表格的更改,此解決方案更具可擴展性。 您不必創建更多宏,只需更改XML規則即可。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM