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?

5
  • Format(Cells(ActiveCell.Row, 2).Value, "0000000000"). Commented Jun 14, 2019 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 ! Commented Jun 14, 2019 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? Commented Jun 15, 2019 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! Commented Jun 16, 2019 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! Commented Jun 16, 2019 at 21:26

1 Answer 1

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
Sign up to request clarification or add additional context in comments.

7 Comments

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
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!
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 ?
Open ActiveWorkbook.Path & "\Whatever.csv" For Output As FileNum
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.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.