vba 将 Excel 行输出到一系列文本文件
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/7149539/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Outputting Excel rows to a series of text files
提问by Wayne Haworth
Inside Excel, I have a list of article names in column A, and a disclaimer inside column B. Now for each article in column A, I would like to create a text file, were A is the title of the file and B, the disclaimer, is the contents of the file.
在 Excel 中,我在 A 列中有一个文章名称列表,在 B 列中有一个免责声明。现在对于 A 列中的每篇文章,我想创建一个文本文件,A 是文件的标题,B 是免责声明,是文件的内容。
Is this possible?
这可能吗?
The idea is that I have several hundred of these, and I would like to make this easier on myself.
这个想法是我有几百个这样的,我想让自己更容易。
If Excel is not ideal for this, can anyone suggest an alternative? (possibly Notepad++ has a feature that can help?)
如果 Excel 不适合于此,有人可以提出替代方案吗?(可能 Notepad++ 有一个可以提供帮助的功能?)
回答by transistor1
Sub Export_Files()
Dim sExportFolder, sFN
Dim rArticleName As Range
Dim rDisclaimer As Range
Dim oSh As Worksheet
Dim oFS As Object
Dim oTxt As Object
'sExportFolder = path to the folder you want to export to
'oSh = The sheet where your data is stored
sExportFolder = "C:\Disclaimers"
Set oSh = Sheet1
Set oFS = CreateObject("Scripting.Filesystemobject")
For Each rArticleName In oSh.UsedRange.Columns("A").Cells
Set rDisclaimer = rArticleName.Offset(, 1)
'Add .txt to the article name as a file name
sFN = rArticleName.Value & ".txt"
Set oTxt = oFS.OpenTextFile(sExportFolder & "\" & sFN, 2, True)
oTxt.Write rDisclaimer.Value
oTxt.Close
Next
End Sub
回答by brettdj
Another approach using variant arrays for speed, and an alternative to the FileSystemObject
given only file creation is needed.
另一种使用变体数组来提高速度的方法,并且需要替代给FileSystemObject
定的文件创建。
Sub DataDump()
Dim X
Dim lngRow As Long
Dim StrFolder As String
StrFolder = "C:\temp"
X = Range([a1], Cells(Rows.Count, 2).End(xlUp))
For lngRow = 1 To UBound(X)
Open StrFolder & "\" & X(lngRow, 1) & ".txt" For Output As #1
Write #1, X(lngRow, 2)
Close #1
Next
End Sub
回答by PAujla
I do not have enough Rep to comment on other people's post yet so I have to post this as an answer. The accepted answer by @transistor1 works; however, in Excel 2010 need to change
我还没有足够的代表来评论其他人的帖子,所以我必须将此作为答案发布。@transistor1 接受的答案有效;但是,在 Excel 2010 中需要更改
Set oSh = Sheet1
Set oSh = Sheet1
to Set oSh = ThisWorkbook.Worksheets("worksheet")
到 Set oSh = ThisWorkbook.Worksheets("worksheet")
Where "worksheet" is the name of the worksheet the data is on.
其中“工作表”是数据所在的工作表的名称。