Word VBA:表格单元格范围到文本文件
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10873080/
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
Word VBA: Table cell range to text file
提问by Daan
I'd like to copy a table like thisin a word document and extract only the track titles and composers. The selecting of the range goes according to plan:
我想复制一个表像这样在Word文档中,只提取曲目标题和作曲家。范围的选择按计划进行:
Dim myCells As Range
With ActiveDocument
Set myCells = .Range(Start:=.Tables(1).Cell(2, 3).Range.Start, _
End:=.Tables(1).Cell(.Tables(1).Rows.Count, 3).Range.End)
myCells.Select
End With
Now, when I copy this selection manually and paste it into notepad, I get exactly what I want:
现在,当我手动复制此选择并将其粘贴到记事本中时,我得到了我想要的:
Title
Composer
Title
Composer
etc.
However, I want to write this selection automatically into a text file. When I try to do this, all content is stuffed in one line of text and little squares (paragraph signs?) pop up everywhere.
但是,我想将此选择自动写入文本文件。当我尝试这样做时,所有内容都塞在一行文本中,到处都是小方块(段落标志?)。
How would be I be able to get the result of the manual copying, using VBA?
我怎样才能使用 VBA 获得手动复制的结果?
采纳答案by Siddharth Rout
Try this
尝试这个
Sub Allmusic()
Dim filesize As Integer
Dim FlName As String, tempStr As String
Dim i As Long
Dim MyAr() As String
'~~> Name of Output File
FlName = "C:\Sample.Txt"
'~~> Get a free file handle
filesize = FreeFile()
'~~> Open your file
Open FlName For Output As #filesize
With ActiveDocument
For i = 2 To .Tables(1).Rows.Count
'~~> THIS LINE WILL NOT REFLECT CORRECTLY IN THE BROWSER
'~~> PLEASE REFER TO THE SCREENSHOT OR THE ATTACHED FILE
tempStr = Replace(.Tables(1).Cell(i, 3).Range.Text, "", "")
If InStr(1, tempStr, Chr(13)) Then
MyAr = Split(tempStr, Chr(13))
Print #filesize, MyAr(0)
Print #filesize, MyAr(1)
Else
Print #filesize, tempStr
End If
Print #filesize, ""
Next i
End With
Close #filesize
End Sub
SNAPSHOT
快照
SAMPLE FILE
样本文件
Download the file and run the procedure Sub Allmusic()
下载文件并运行程序 Sub Allmusic()
OUTPUT
输出
HTH
HTH