自定义导出Excel到文本文件

时间:2014-10-23 18:26:07

标签: excel csv

是否有方法或脚本允许我从Excel文件中获取单个数据,并将其导出到文本文件,以便每个字段由逗号和单词空间 - 在一个动作中。在Excel中使用另存为csv仍然需要您在编辑器中打开文件并执行搜索/替换以实现此目的,但这需要第二步,不必要的步骤。

从Excel导出COLUMN时我想要的结果如下所示:

领域,领域,领域,领域,领域,领域,领域,领域,领域,领域,领域,领域,领域,领域,领域,领域,领域,领域,领域,领域,领域,领域,字段,字段,字段,字段,字段,字段,字段,字段,字段,字段,字段,字段,字段,字段,字段,字段,字段,字段,字段,字段

2 个答案:

答案 0 :(得分:0)

或许这样的事情?

提供您自己的文件路径和文件名。假设数据从Sheet1中col B的第2行开始,但您可以更改这些变量以适应代码。

Sub WriteCSVFile()

Dim ws As Worksheet
Dim fName As String, Txt1 As String
Dim fRow As Long, lRow As Long, Rw As Long
Dim Col As Long

Set ws = Sheets("Sheet1")
fName = "C:\yourpath\yourfilename.csv"
fRow = 2
Col = 2
Txt1 = ""

    With ws
        lRow = .Cells(Rows.Count, Col).End(xlUp).Row

        Open fName For Output As #1

            For Rw = fRow To lRow
                Txt1 = .Range(.Cells(Rw, Col), .Cells(Rw, Col))
                    If Rw = lRow Then
                        Print #1, Txt1
                    Else
                        Print #1, Txt1 & ", ";
                    End If
            Next Rw

        Close #1

        MsgBox ".csv file exported"

    End With
End Sub

如果您需要进一步说明,可以使用教程here

答案 1 :(得分:0)

Sub WriteCSVFile()

'声明变量 Dim ws As Worksheet Dim fName As String,Txt1 As String Dim fRow As Long,lRow As Long,Rw As Long Dim Col As Long

'获取活动表 设置ws = ActiveWorkbook.ActiveSheet

'询问用户输出文件 fName = Application.GetOpenFilename()

'如果没有指定文件则停止处理 如果fName =" False"然后退出Sub

'开始行 fRow = 1

'开始列 Col = 1

'输出温度 Txt1 =""

With ws
    ' Get data from sheet
    lRow = .Cells(Rows.Count, Col).End(xlUp).Row

    ' Open output file
    Open fName For Output As #1

        ' Loop rows of data
        For Rw = fRow To lRow
            ' Store data in temp
            Txt1 = .Range(.Cells(Rw, Col), .Cells(Rw, Col))
                ' Check if end of dataset and write data to output accordingly 
                If Rw = lRow Then
                    Print #1, Txt1
                Else
                    Print #1, Txt1 & ", ";
                End If
        Next Rw

    ' Close output file
    Close #1

     ' Alert user of completion
    MsgBox ".csv file exported"

End With

End Sub