1

I have this code:

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

But all the info became without left zeros in the output csv generated:

Intended:

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 Export: Without the needed left ZERO 000

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

How can I have the leading zeroes?

Community
  • 1
  • 1
Epontes
  • 15
  • 6
  • `Format(Cells(ActiveCell.Row, 2).Value, "0000000000")`. – BigBen Jun 14 '19 at 20:01
  • But the firt line of the csv is with the needed zero in the lenght, after de second row the vba code seems to remove the zeros ! – Epontes Jun 14 '19 at 20:04
  • You export with ";" as divider, but your example shows blanks instead. Are the leading zeros missed directly in the CSV-file or only after reopening the CSV with Excel? – Asger Jun 15 '19 at 10:55
  • The leading zeros are missed in the csv opened iin excel, but the original file as the leading zeros before export to the csv, the first row is ok you can see the leading zeros, but from de second one the error exists! – Epontes Jun 16 '19 at 21:23
  • Open in NotePad = All OK 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 open in csv via excel = No leading zeros from the second row! – Epontes Jun 16 '19 at 21:26

1 Answers1

2

Export

If you need leading zeros, then Format should help.

You should also avoid selecting or activating anything.
Therefore I used a variable "i" for a loop over all rows.

As filenumber 1 may already be in use, it is better to use 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

Import

When you import this CSV into Excel, Excel recognises the numbers as numbers.
Therefore you have two options:

  • keep it as number and give it a customized number format,
    e. g. "0000000000" shows numbers with leading zeros
  • import it as text string by following VBA code

Please adapt the filepath and filename to your needs.

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

Path of the Excel file

Please either use the ActiveWorkbook, which is the currently active file, or ThisWorkbook, which is the file with your VBA code. They are the same, if the file containing your VBA code also is the active file.

Use its Path, add a backslash "\" and add the desired CSV filename (e. g. "APR CSV Renault.CSV").

Experiment with his:

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
Asger
  • 3,822
  • 3
  • 12
  • 37
  • Thanks, but not always the reference as the same lenght ( 0000000000 ), can you help me, i'm new to VBA. The result is the same, only the first row as the leading zeros!! 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 – Epontes Jun 16 '19 at 21:20
  • Open in NotePad = All OK 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 open in csv via excel = No leading zeros from the second row! – Epontes Jun 16 '19 at 21:28
  • I have this vba code in excel, but i need to make some changes so that the file can be used by anyone, in this case the vba code is only for my folder/PC. FileNum = FreeFile Open Range("E1").Value For Output As fileNum Where: Cell E1 contains c:\users\xx\xx\APR CSV Renault.CSV How can I have the vba code to output the .csv to the same path of the .xls file for any that as this file in is PC ? – Epontes Jul 04 '19 at 13:35
  • Sorry to ask, but where do i feet the code, i'm new in vba to export? – Epontes Jul 04 '19 at 20:52
  • 1
    `Open ActiveWorkbook.Path & "\Whatever.csv" For Output As FileNum` – Asger Jul 04 '19 at 21:00
  • In the Export language how can I export to a .txt file witg tab delimited layout ? – Epontes Mar 23 '21 at 20:33
  • 1
    Then you get a tab-delimited textfile by just replacing all `";"` by `Chr(9)`. This works independent of the file extension, which may be .csv oder .txt. – Asger Mar 24 '21 at 10:38