【问题标题】:Keeping correct time format when uploading Excel data to Mysql database将 Excel 数据上传到 Mysql 数据库时保持正确的时间格式
【发布时间】:2022-01-04 23:03:38
【问题描述】:

我有以下格式的 excel 数据:

当我单击 UploadData 按钮时,此数据将上传到我连接的 SQL 数据库中。这仅在上传整数和字符串时有效,当我尝试将日期推送到数据库时出现以下错误:

运行 VBA 代码时,它似乎忽略了我在 Excel 工作表中应用日期列的自定义日期格式(“yyyy-mm-dd”),以使其格式正确。如何编辑我的 VBA 代码以使日期列数据采用“yyyy-mm-dd”格式,我认为它应该与我的代码中 For 循环中的“查询”变量有关,以便当它运行查询,它将 Date1 的值设置为正确的时间格式。 注意:在查询变量下,我包含了一个我在 excel 表中使用的公式,它允许我以正确的格式提取日期值,尽管我无法在 VBA 中正确声明它而不会出错

Sub UploadGsaData()
' Create the required variables
Dim query As String 'Variable for SQL query
Dim Date1 As String
Dim Address1 As String
Dim Mobile1 As Integer
Dim Salary1 As Integer
Dim TRow As Long
Dim CRow As Long



        ' Do not update the cells on the current sheet, this is performed after the SQL query
         Application.ScreenUpdating = False

         ' Unprotect sheet to allow SQL changes to be made
         ActiveSheet.Unprotect
         
         ' Send the ending row value
         TRow = 7

         ' Inititate For Loop to iterate table of data
         For CRow = 3 To TRow
                
                 Date1 = Sheets("Sheet1").Range("B" & CRow).Value
                 Address1 = Sheets("Sheet1").Range("C" & CRow).Value
                 Mobile1 = Sheets("Sheet1").Range("D" & CRow).Value
                 Salary1 = Sheets("Sheet1").Range("E" & CRow).Value

                 query = "REPLACE INTO testdata(Date, Address, Mobile, Salary) VALUES('" & Date1 & "', '" & Address1 & "', '" & Mobile1 & "', '" & Salary1 & "')"
                 '="REPLACE INTO operations_logbook(date_time, category, description, logged_by) VALUES('"&TEXT(B3,"yyyy-mm-dd")&"', '"&D6&"', '"&D10&"', '"&D8&"')"
         
                 ' Call mysql query function to run query to upload log to database ( called a different name as different driver)
                 Call server_2_query_mysql_database(server2, database1, query, ActiveSheet.Range("A1"))
         
          Next
          
          

         ' Reapply the Sheet protection now that the query is complete
         ActiveSheet.Protect

         ' Update the Excel sheet so that any new data is updated
         Application.ScreenUpdating = True


End Sub

【问题讨论】:

    标签: sql excel vba


    【解决方案1】:

    改变这个...

    Date1 = Sheets("Sheet1").Range("B" & CRow).Value
    

    ...到这个...

    Date1 = Sheets("Sheet1").Range("B" & CRow).Text
    

    【讨论】:

    • 谢谢大家,真不敢相信我错过了! :) 我会尽快接受答案!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-05-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-02-18
    • 1970-01-01
    相关资源
    最近更新 更多