简体   繁体   中英

Save columns to csv VBA

I have the following columns:

Time    NumberOfTasks   TimeOfCapture
0:00                     29-07-15 9:15
0:01                     29-07-15 9:15
0:02                     29-07-15 9:15
0:03                     29-07-15 9:15
0:04                     29-07-15 9:15
0:05                     29-07-15 9:15
0:06                     29-07-15 9:15
0:07    1                29-07-15 9:15

I would like to write these columns to a csv file and save it on my disk. I do the following:

For i = 1 To LastRow
    For j = 1 To 3
        If j = 3 Then
            CellData = CellData + Trim(Worksheets("Output").Cells(i, j).Text)
            Else
                CellData = CellData + Trim(Worksheets("Output").Cells(i, j).Text) + ","
                End If
            Next j
        Write #2, CellData
        CellData = ""
    Next i
    Close #2
    MsgBox ("Done")

The output that I get from this in my csv file:

Time       NumberOfTasks    TimeOfCapture
0                           29-7-2015 9:15
6,94E+10                    29-7-2015 9:15
1,39E+11                    29-7-2015 9:15

What is wrong with the first time column?

In VBA & is the operator for combining strings (not + like in other languages). Try to change your code like that:

For i = 1 To LastRow

    For j = 1 To 3

        If j = 1 Then
            CellData = Format(CellData, "HH:MM") + Trim(Worksheets("Output").Cells(i, j).Value) + ","
        ElseIf j = 3 Then
            CellData = CellData + Trim(Worksheets("Output").Cells(i, j).Value)
        Else
            CellData = CellData + Trim(Worksheets("Output").Cells(i, j).Value) + ","
        End If
    Next j

    Write #2, CellData
    CellData = ""

Next i

Close #2
MsgBox ("Done")

The following works:

For i = 1 To LastRow
    For j = 1 To 3
        If j = 3 Then
            CellData = CellData + Trim(Worksheets("Output").Cells(i, j).Text)
            Else
                CellData = CellData + Trim(Worksheets("Output").Cells(i, j).Text) & ","
                End If
            Next j
        Write #2, CellData
        CellData = ""
    Next i
    Close #2
    MsgBox ("Done")

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM