将列保存到csv VBA

时间:2015-07-30 12:38:10

标签: excel vba

我有以下专栏:

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

我想将这些列写入csv文件并将其保存在我的磁盘上。我做了以下事情:

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")

我在csv文件中从中获得的输出:

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

第一次列有什么问题?

2 个答案:

答案 0 :(得分:0)

在VBA中&是组合字符串的运算符(与其他语言不同,不是+)。尝试改变你的代码:

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")

答案 1 :(得分:0)

以下作品:

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")