如何从Excel文件以文本格式将前导零导出到csv文件?

时间:2019-06-14 19:49:32

标签: excel vba

我有这个问题:

Sub GravarArquivoCSV()

Open Range("E1").Value For Output As 1

Sheets("APR_CSV").Activate
Range("A1").Select

Do While ActiveCell.Text <> ""
    Print #1, ActiveCell.Value & ";" & Cells(ActiveCell.Row, 2).Value & ";" & Cells(ActiveCell.Row, 3).Value & ";" & Cells(ActiveCell.Row, 4).Value
    Cells(ActiveCell.Row + 1, ActiveCell.Column).Select
Loop

MsgBox "Arquivo gerado com sucesso!", vbInformation, "OK"
Close 1

Sheets("Autoline Controlo Compras").Activate
End Sub

但是所有信息在生成的csv输出中都没有左零:

预期:

62013227 001148160R 1 41563 M02-UL-98
62013227 8200212598 2 42426 M25-BI-26
62013227 0000066444 1 42490 C19-RA-68
62013227 8200725845 1 43858 BJ1 0028 11485
62013227 7701475837 1 43858 BJ1 0028 11485
62013227 0000474796 1 43858 BJ1 0028 11485
62013227 8200661217 2 43858 BJ1 0028 11485

CSV导出:没有需要的零零

62013227 001148160R 1 41563 M02-UL-98
62013227 8200212598 2 42426 M25-BI-26
62013227 66444 1 42490 C19-RA-68
62013227 8200725845 1 43858 BJ1 0028 11485
62013227 7701475837 1 43858 BJ1 0028 11485
62013227 474796 1 43858 BJ1 0028 11485
62013227 8200661217 2 43858 BJ1 0028 11485

如何更正此vba代码,以便可以得到前导零?

1 个答案:

答案 0 :(得分:0)

导出

如果您需要前导零,那么Format应该会有所帮助。

您还应该avoid selecting or activating anything
因此,我将变量“ i”用于所有行的循环。

由于文件号1可能已经在使用中,最好使用FreeFile

Sub GravarArquivoCSV()
    Dim fileNum As Long
    Dim i As Long

    fileNum = FreeFile
    Open Range("E1").Value For Output As fileNum

    With Sheets("APR_CSV")
        i = 1
        Do While .Cells(i, "A").Text <> ""
            Print #FileNum, .Cells(i, "A").Value & ";" & _
                      Format(.Cells(i, "B").Value, "0000000000") & ";" & _
                      .Cells(i, "C").Value & ";" & _
                      .Cells(i, "D").Value
            i = i + 1
        Loop
    End With
    Close fileNum

    MsgBox "Arquivo gerado com sucesso!", vbInformation, "OK"
    Sheets("Autoline Controlo Compras").Activate
End Sub

导入

将此CSV导入Excel时,Excel会将数字识别为数字。
因此,您有两个选择:

  • 将其保留为数字并为其自定义数字格式,
    e。 G。 “ 0000000000”显示带有前导零的数字
  • 按照VBA代码将其作为文本字符串导入

请根据您的需要调整文件路径和文件名。

Public Sub ImportCSV()
    Dim wb As Workbook
    Set wb = Application.Workbooks.Add

    With wb.Worksheets(1).QueryTables.Add( _
        Connection:="TEXT;" & Application.DefaultFilePath & "\APR_CSV.csv", _
        Destination:=wb.Worksheets(1).Range("A1"))
        .Name = "APR_CSV"
        .FieldNames = False
        .RowNumbers = False
        .FillAdjacentFormulas = False
        .PreserveFormatting = True
        .RefreshOnFileOpen = False
        .RefreshStyle = XlCellInsertionMode.xlInsertDeleteCells
        .SavePassword = False
        .SaveData = True
        .AdjustColumnWidth = True
        .RefreshPeriod = 0
        .TextFilePromptOnRefresh = False
        .TextFilePlatform = XlPlatform.xlWindows
        .TextFileStartRow = 1
        .TextFileParseType = XlTextParsingType.xlDelimited
        .TextFileTextQualifier = XlTextQualifier.xlTextQualifierNone
        .TextFileConsecutiveDelimiter = False
        .TextFileTabDelimiter = False
        .TextFileSemicolonDelimiter = True
        .TextFileCommaDelimiter = False
        .TextFileSpaceDelimiter = False
        .TextFileColumnDataTypes = Array( _
            XlColumnDataType.xlGeneralFormat, _
            XlColumnDataType.xlTextFormat, _
            XlColumnDataType.xlGeneralFormat, _
            XlColumnDataType.xlTextFormat)
        .TextFileDecimalSeparator = "."
        .TextFileThousandsSeparator = ","
        .TextFileTrailingMinusNumbers = True
        .Refresh BackgroundQuery:=False
        .Delete
    End With
End Sub

Excel文件的路径

请使用ActiveWorkbook(这是当前活动的文件)或ThisWorkbook(这是带有您的VBA代码的文件)。如果包含您的VBA代码的文件也是活动文件,则它们是相同的。

使用其Path,添加反斜杠“ \”并添加所需的CSV文件名(例如“ APR CSV Renault.CSV”)。

他的实验:

Private Sub DebugMyPaths
' always the file with THIS VBA code:
Debug.Print ThisWorkbook.Path & "\" & ThisWorkbook.Name
Debug.Print ThisWorkbook.FullName

' always the active Excel file:
Debug.Print ActiveWorkbook.Path & "\" & ActiveWorkbook.Name
Debug.Print ActiveWorkbook.FullName
End Sub