使用宏将数据从excel复制到csv

时间:2013-07-25 03:52:35

标签: excel excel-vba csv vba

我想将数据从excel复制到csv,但似乎无法找到正确的逻辑。以下是我想要复制数据的方法。例如,我想将excel的单元格D4中的数据复制到csv中的A4。我想重复这个,直到D列中的单元格为空。

"Excel ---> CSV
"D4-->A4
"F4&G4-->B4
"K4-->E4
"L4-->F4
"N4-->G4
"P4-->I4

很抱歉,我刚开始编写宏时问这样一个基本问题。以下是我目前的代码。这会创建csv文件,但不会填充我需要的数据。

Sub csvfile()

Dim fs As Object, a As Object, i As Integer, s As String, t As String, l As String, mn As String
Set fs = CreateObject("Scripting.FileSystemObject")
sUser = Environ("username")
Set a = fs.CreateTextFile("S:\ics\jellybean\" & sUser & ".csv", True)

For r = 4 To Range("A65536").End(xlUp).Row
    s = ""
    c = 6
    While Not IsEmpty(Cells(r, c))
        s = s & Cells(r, c) & ","
        c = c + 1
    Wend
    a.writeline s 'write line
Next r

End Sub

1 个答案:

答案 0 :(得分:1)

像这样的东西使用数组并且非常有效(假设您的数据具有从D到P的相同列长度,用于感兴趣的列)

Sub csvfile()

Dim fs As Object
Dim a As Object
Dim lngRow As Long
Dim X

Set fs = CreateObject("Scripting.FileSystemObject")
Set a = fs.CreateTextFile("c:\temp\" & Environ("username") & ".csv", True)
X = Range([d4], Cells(Rows.Count, "P").End(xlUp)).Value2

For lngRow = 1 To UBound(X)
a.writeline X(lngRow, 1) & "," & X(lngRow, 3) & X(lngRow, 4) & ",,," & X(lngRow, 8) & "," & X(lngRow, 9) & "," & X(lngRow, 11) & ",," & X(lngRow, 13)
Next
a.Close

End Sub