使用宏将CSV单元格放在Excel中

时间:2010-12-30 17:52:03

标签: excel vba csv excel-vba vbscript

所以,我有一个宏来将数据导出为CSV格式,并且它工作得很好(底部的代码)。问题是我投入的数据。当我把数据放在其中时出来

  

名字,姓氏,用户名,密码,描述

我想改变它,所以我得到

  

名字姓氏,名字,姓氏,用户名,密码,说明

我想要做的是操纵现有的宏来实现这一目标。我不是很擅长VBS所以任何输入或正确方向的推动都会很棒。

谢谢!

代码来自用户Chance2 http://www.excelforum.com/excel-programming/679620-set-up-macro-to-export-as-csv-file.html。公平公正,作者应该被正确归因。我为使这些声音专有而道歉。

Sub Make_CSV()
Dim sFile As String
Dim sPath As String
Dim sLine As String

Dim r As Integer
Dim c As Integer

    r = 1 'Starting row of data

    sPath = "C:\CSVout\"
    sFile = "MyText_" & Format(Now, "YYYYMMDD_HHMMSS") & ".CSV"

    Close #1
    Open sPath & sFile For Output As #1
    Do Until IsEmpty(Range("A" & r))
    'You can also Do Until r = 17 (get the first 16 cells)
        sLine = ""
        c = 1
        Do Until IsEmpty(Cells(1, c))
           'Number of Columns - You could use a FOR / NEXT loop instead
            sLine = sLine & """" & Replace(Cells(r, c), ";", ":") & """" & ","
            c = c + 1
        Loop
        Print #1, Left(sLine, Len(sLine) - 1) 'Remove the trailing comma
        r = r + 1
    Loop
    Close #1
End Sub

1 个答案:

答案 0 :(得分:2)

最简单的改变是为sLine分配'Firstname Lastname'连接,即:

Do Until IsEmpty(Range("A" & r))
'You can also Do Until r = 17 (get the first 16 cells)
    sLine = """" & Replace(Cells(r,1) & " " & Cells(r,2), ";", ":") + ""","
    c = 1
    Do Until IsEmpty(Cells(1, c))
       'Number of Columns - You could use a FOR / NEXT loop instead
        sLine = sLine & """" & Replace(Cells(r, c), ";", ":") & """" & ","
        c = c + 1
    Loop
    Print #1, Left(sLine, Len(sLine) - 1) 'Remove the trailing comma
    r = r + 1
Loop