从excel创建文本文件

时间:2013-01-18 08:22:14

标签: excel excel-vba excel-2007 excel-formula excel-2010 vba

需要从Excel行创建文本文件。 第1列应包含文件名,第2列应包含文本文件的内容。每行将为该新文本文件提供新文件名或新内容。此外,文本的内容应分成几行。 怎么做到这一点?谢谢。

1 个答案:

答案 0 :(得分:2)

编辑的解决方案,文本分隔为行。

对于样本,使用以下字符:

  

:,/ |

根据需要将新分隔符添加到RegEx模式。完整代码如下:

Sub Text2Files()

Dim FileStream As Object
Dim FileContent As String
Dim i As Long
Dim SavePath As String
Dim RegX_Split As Object

Set RegX_Split = CreateObject("VBScript.RegExp")
RegX_Split.Pattern = "[\;\:\,\\\/\|]" 'List of used line seperators as \X
RegX_Split.IgnoreCase = True
RegX_Split.Global = True

Set FileStream = CreateObject("ADODB.Stream")
SavePath = "D:\DOCUMENTS\" 'Set existing folder with trailing "\"

For i = 1 To ThisWorkbook.ActiveSheet.Cells(1, 1).CurrentRegion.Rows.Count

    FileContent = RegX_Split.Replace(ThisWorkbook.ActiveSheet.Cells(i, 2).Text, vbNewLine)
    FileStream.Open
    FileStream.Type = 2 'Text
    FileStream.Charset = "UTF-8" 'Change encoding as required
    FileStream.WriteText FileContent
    FileStream.SaveToFile SavePath & ThisWorkbook.ActiveSheet.Cells(i, 1).Text, 2 'Will overwrite the existing file
    FileStream.Close

Next i

End Sub
  1. 了解有关ADO Stream Object的更多信息: http://www.w3schools.com/ado/ado_ref_stream.asp
  2. 初学者的RegEx: http://www.jose.it-berater.org/scripting/regexp/regular_expression_syntax.htm
  3. 带有上述代码的示例文件位于:https://www.dropbox.com/s/kh9cq1gqmg07j20/Text2Files.xlsm