简体   繁体   English

使用宏将数据从Excel复制到CSV

[英]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. 我想将数据从excel复制到csv,但似乎找不到正确的逻辑。 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. 例如,我想将Excel单元格D4中的数据复制到csv中的A4。 I want to repeat this until a cell in column D is empty. 我想重复此操作,直到D列中的单元格为空。

"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. 这将创建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

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) 这样的事情使用数组的并且非常有效(假设您感兴趣的列的数据从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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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