簡體   English   中英

在 VBA 中打開 CSV 文件時如何保持前導零

[英]How to keep leading zeros when opening CSV file in VBA

我有一個 VBA 代碼,可以快速從 CSV 文件傳輸數據,但不幸的是排除了前導零(例如 000123 轉換為 123)

Filename = "c:\text.csv"
Dim wbI As Workbook, wbO As Workbook
Dim wsI As Worksheet
Set wbI = ThisWorkbook
Set wsI = wbI.Sheets("Temp")
Filename = "c:\text.csv"

Set wbO = Workbooks.Open(Filename) 
wbO.Sheets(1).Cells.Copy wsI.Cells
wbO.Close SaveChanges:=False

我在打開 csv 文件 > Cells.NumberFormat = "@" 后嘗試添加以下內容

Set wbO = Workbooks.Open(Filename) 
Cells.NumberFormat = "@"
wbO.Sheets(1).Cells.Copy wsI.Cells
wbO.Close SaveChanges:=False

不幸的是,它不起作用,我看到的問題是文件打開后已經缺少前導零

是否可以在不影響前導零的情況下打開文件並將所有數據顯示為文本以保持前導零?

請嘗試這種方式:

Sub testOpenWithLZeroTxt()
 Dim Filename As String, wbI As Workbook, wbO As Workbook, wsI As Worksheet
 Dim arrTXT, nrCol As Long, arr(), i As Long, sep As String, lineSep As String
 Dim allTxt As String, txtStr As Object, fileTxt As String, fs As Object, f As Object, ts As Object
 
 Set wbI = ThisWorkbook
 Set wsI = wbI.Sheets("Temp")
 Filename = "c:\text.csv"
    fileTxt = Split(Filename, ".")(0) & ".txt" 'create a helper txt file using the csv string content
    
    Set fs = CreateObject("Scripting.FileSystemObject")
    allTxt = fs.OpenTextFile(Filename, 1).ReadAll 'reed the csv file content
    fs.CreateTextFile fileTxt
    Set f = fs.GetFile(fileTxt)
    Set ts = f.OpenAsTextStream(2, -2)
        ts.write allTxt                          'write the csv content in a newly created txt file
    ts.Close
    
    'Check the number of text file columns:_______
    sep = vbLf ' if not working you can try vbCrLf. It works so on your file
    lineSep = ","  'it my be vbTab, ";" etc. It works so on your file
    arrTXT = Split(allTxt, sep)
    nrCol = UBound(Split(arrTXT(0), lineSep))
    '_____________________________________________
    
    ReDim arr(nrCol) 'redim the format array
    For i = 0 To nrCol
        arr(i) = Array(i + 1, 2) 'fill the format array with variant for TEXT Format!
    Next
    'open the helper txt file as you need:
    Workbooks.OpenText Filename:=fileTxt, origin:=437, startRow:=1, _
                DataType:=xlDelimited, Tab:=False, Comma:=True, FieldInfo:=arr()
    Set wbO = ActiveWorkbook
    'wbO.Sheets(1).cells.Copy wsI.Range("A1") 'copy the content
    wbO.Close SaveChanges:=False              'close the file
    Kill fileTxt                              'kill helper txt file
End Sub

編輯

我改變了代碼理念。 它將首先讀取字符串變量中的 csv 內容,並使用獲得的字符串創建一個 txt 文件並將其作為文本打開,這當然應該可以工作。 它適用於 csv 文件中的任意數量的列。

csv 文件中的換行符是 unix LF。 這對應於 chr(10)。

由於第一行的列數和下一行的列數不一致,所以使用了一點偏差。 通過將第一行中的列數加倍來創建一個數組。

Sub test()
    Dim Ws As Worksheet
    Dim Fn As String
    Dim Arr As Variant
    
    Fn = "Example.csv"
    'Fn = "c:\text.csv"
    Set Ws = Sheets("Temp")
    
    Arr = getDatFromCsv(Fn)
    
    With Ws
        .Cells.NumberFormat = "@"
        .Cells = Empty
        .Range("a1").Resize(UBound(Arr, 1) + 1, UBound(Arr, 2) + 1) = Arr
    End With
    
    
End Sub
Function getDatFromCsv(strFn As String) As Variant
    Dim vR() As String
    Dim i As Long, r As Long, j As Integer, c As Integer
    Dim objStream  As Object
    Dim strRead As String
    Dim vSplit, vRow
    Dim s As String
    
    Set objStream = CreateObject("ADODB.Stream")

    With objStream
        .Charset = "utf-8"
        .Open
        .LoadFromFile strFn
         strRead = .ReadText
        .Close
    End With
    
    vSplit = Split(strRead, Chr(10)) 'Unix Lf ~~> chr(10)
    r = UBound(vSplit)
    c = UBound(Split(vSplit(0), ",", , vbTextCompare))
    ReDim vR(0 To r, 0 To c * 2)
    
    For i = 0 To r
        vRow = Split(vSplit(i), ",", , vbTextCompare)
        'If UBound(vRow) = c Then 'if it is empty line, skip it
            
            For j = 0 To UBound(vRow)
                vR(i, j) = vRow(j)
            Next j
        'End If
    Next i
    getDatFromCsv = vR
    
    Set objStream = Nothing

End Function

結果圖像

在此處輸入圖像描述

請改用OpenText 方法

最重要的參數是FieldInfo 你需要通過:

包含單個數據列的解析信息的數組。 解釋取決於 DataType 的值。 當數據被分隔時,這個參數是一個二元素數組 arrays,每個二元素數組指定特定列的轉換選項。 第一個元素是列號(從 1 開始),第二個元素是XlColumnDataType常量之一,指定如何解析列

換句話說,每列前導零都必須定義為xlTextFormat

我建議錄制宏。 ;) 加載文本數據的選項,您可以在“ Data ”選項卡 ->... -> From text/CSV下找到

暫無
暫無

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

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