我有一个word文档,其中包含我想要解析为excel文件的数据。源文件长达数百页。我一直在使用VBA,但我刚开始学习该语言,并且在尝试输入.doc文件时遇到了很多困难。我能够使用打开和行输入语句从.txt文件中检索,但在尝试.doc文件时只能乱码。
我已经包含两个屏幕截图链接。
第一个是输入数据样本的屏幕截图 http://img717.imageshack.us/i/input.jpg/
第二个是我想要的输出的截图 http://img3.imageshack.us/i/outputg.jpg/
我开发了一个我想要完成的算法。我只是编码困难。下面是我开发的伪代码。
Variables:
string line = blank
series_title = blank
folder_title = blank
int series_number = 0
box_number = 0
folder_number = 0
year = 0
do while the <end_of_document> has not been reached
input line
If the first word in the line is “series”
store <series_number>
store the string after “:”into the <series_title>
end if
call parse_box(rest of line)
output < series_number > <series_title> < box_number > < folder_number ><folder_title> <year>
end do while
function parse_box(current line)
If the first word in the line is “box”
store <box_number>
end if
call parse_folder(rest of line)
end function
function parse_folder(current line)
If first word is “Folder”
store <folder_number>
end if
call parse_folder_title(rest of line)
end function
function parse_folder_title_and_year(current line)
string temp_folder_title
store everything as <temp_folder_title> until end of line
if last word in <temp_folder_title> is a year
store <year>
end if
if < temp_folder_title> is empty/blank
//use <folder_title> from before
else
<folder_title> is < temp_folder_title> minus <year>
end if
end parse_folder_title_and_year
提前感谢您的所有帮助和建议
答案 0 :(得分:4)
fopen和输入命令通常只适用于纯文本文件(您可以在记事本中阅读的内容)。如果要以编程方式从Microsoft Word文档中读取,则必须将Microsoft Word 12.0对象库(或系统上的最新版本)添加到VBAProject引用中,并使用Word API打开和读取文档。 / p>
Dim odoc As Word.Document
Set odoc = oWrd.Documents.Open(Filename:=DocumentPath, Visible:=False)
Dim singleLine As Paragraph
Dim lineText As String
For Each singleLine In ActiveDocument.Paragraphs
lineText = singleLine.Range.Text
'Do what you've gotta do
Next singleLine
Word没有“Lines”的概念。您可以阅读文本范围,段落和句子。尝试并找到最适合将输入文本放入可管理块中的方法。
答案 1 :(得分:0)
这是实际起作用的代码。
'Create a New Object for Microsoft Word Application
Dim objWord As New Word.Application
'Create a New Word Document Object
Dim objDoc As New Word.Document
'Open a Word Document and Set it to the newly created object above
Set objDoc = objWord.Documents.Open(Filename:=DocFilename, Visible:=False)
Dim strSingleLine As Paragraph
Dim strLineText As String
For Each strSingleLine In objDoc.Paragraphs
strLineText = strSingleLine.Range.Text
'Do what you've gotta do
Next strSingleLine