0

我使用下面的代码将 CSV 文件从本地文件夹导入到 Access 中的表中。但是,我注意到前导零丢失/被截断。

不知道为什么,因为我的印象是 Access 没有切断零。

我尝试用零填充但不工作。我认为在导入访问期间前导零被截断,因为这是通过代码发生的,不知道如何阻止它。

希望这里的专业人士可以看看:

Option Compare Database
Option Explicit

Sub ImportFileProcedure()
Dim strPathFile As String, strFile As String, strPath As String
Dim strTable As String
Dim xlApp As Object, xlWb As Object, xlWs As Object
Dim lngRow As Long, lngLastRow As Long
Dim rst As DAO.Recordset
strPath = "C:\FOLDER\"
strTable = "TEMP_TBL"
strFile = Dir(strPath & "*.csv")
Set rst = CurrentDb.OpenRecordset(strTable)
Do While Len(strFile) > 0
      strPathFile = strPath & strFile
        Set xlApp = CreateObject("Excel.Application")
        Set xlWb = xlApp.Workbooks.Open(strPathFile)
        Set xlWs = xlWb.Worksheets(1)
        lngLastRow = xlWs.UsedRange.Rows.Count
        For lngRow = 2 To lngLastRow
            rst.AddNew
            rst("SAMPLE") = xlWs.Range("A" & lngRow).Value
            rst("SAMPLE") = xlWs.Range("B" & lngRow).Value
            rst("SAMPLE") = xlWs.Range("C" & lngRow).Value
            rst("SAMPLE") = xlWs.Range("D" & lngRow).Value
            rst("SAMPLE") = xlWs.Range("E" & lngRow).Value
            rst.Update
        Next
    xlApp.Quit
    Set xlApp = Nothing
    Set xlWb = Nothing
    Set xlWs = Nothing
    strFile = Dir()
Loop
rst.Close
Set rst = Nothing
End Sub

感谢您的关注

4

1 回答 1

0

我决定简单地创建一个 UPDATE 查询来添加/填充前导零,在数据加载到表中之后运行 UPDATE。这是我能做的最好的事情,而不是修改上面的代码:

这是 UPDATE 查询的 SQL:

x = left(yourfield & string(8,"0"), 8)

x = right(string(8,"0")& yourfield, 8)

or...

padlen = 8

x = left(yourfield & string(padlen,"0"), padlen)

x = right(string(padlen,"0")& yourfield, padlen)

感谢大家!

于 2012-12-03T20:32:36.010 回答