简体   繁体   中英

Copy data from excel to csv using macro

I want to copy data from excel to csv but cant seem to find the correct logic. Below is how I want to copy the data. For example I want to copy data in cell D4 of excel to A4 in csv. I want to repeat this until a cell in column D is empty.

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

Sorry to ask such a basic question as I just started writing macros. Below is my code currently. This creates the csv file but does not populate the data I need.

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

Somewthing like this uses array's and is very efficient (it assumes your data has the same column length from D to P for the columns of interest)

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

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