对于我的工作,我必须在40个单词的文档(.doc)中找到样式的所有实例。收到文字后,我想将其写入Excel工作表(.xls)的单元格中。
使用我编写的代码,我可以获取该样式的第一个实例,但不能获取下一个实例,它进入无限循环,现在我不知道为什么了(每个文件中约有10个实例)。
你能告诉我我哪里错了吗?
这是我的代码:
'==================================================================
' Declarations
'==================================================================
Dim ObjWord As Object ' Word application object
'==================================================================
' Macro
'==================================================================
Public Sub Macro()
Dim row As Integer
row = 9 'first available row
Set ObjWord = CreateObject("word.application")
Worksheets("Sheet 2").Activate
While (Cells(row, 2).Value <> "End of file list")
Set file = ObjWord.documents.Open(ThisWorkbook.path & ".\" & Cells(row, 1).Hyperlinks(1).Address)
Set currentRange = file.Range
currentRange.Find.ClearFormatting
currentRange.Find.Forward = True
currentRange.Find.Text = ""
currentRange.Find.Style = "MyStyle"
bFind = currentRange.Find.Execute
Do While bFind 'here is the endless loop
row = row + 1
StyleValue= currentRange.Text 'I get stuck with the first value :-(
Rows(row).EntireRow.Insert
Cells(row, 2).Value = StyleValue
bFind = currentRange.Find.Execute
Loop
file.Close
row = row + 1 ' next File
Wend
ObjWord.Quit
End Sub
为了使它对我有用,我必须进行一些更改,这主要是因为我Option Explicit
启用了并声明了所有变量。
但是,在进行遍历时,如果它在第一个查找上循环,则可能是一个问题,那就是您必须将所选内容移到查找之后才能找到下一个。
Do While bFind 'here is the endless loop
row = row + 1
StyleValue= currentRange.Text 'I get stuck with the first value :-(
Rows(row).EntireRow.Insert
Cells(row, 2).Value = StyleValue
currentRange.SetRange currentRange.End, currentRange.End
bFind = currentRange.Find.Execute
Loop
如果那不起作用,我稍后可以弹出一个完整的替换项
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句