作为前言,我不是一个程序员。只是试图为一个宏观使用一个宏观。
目前需要在excel中循环约3700行,并在〜100个Word文档中找到某些单词。
基本上是第1行需要找到"驴"(单元格A1)一词,并搜索单元A4中列出的文档,然后产生找到该单词的次数,如果大于2次,则标记"是"。
我的问题是,有时它会完成,有时在打开下一个文档时,我会收到错误
运行时错误'91':对象变量或块变量未设置
通常重新启动Excel或更改正在搜索的文档的文件路径将其修复为一两个运行。这使我相信这与记忆有关,但我不确定。
有什么想法是什么?谢谢!
这是代码,是的,它是草率的。
Sub FindName()
Dim wrdApp As Object
Dim wrdDoc As Object
Dim maxRowCount As Integer
Dim TP As String
Dim FindWord As String
Dim result As String
Dim RowCount As Integer
Dim i As Long
Dim iCount As Integer
TP = "003"
i = 115
maxRowCount = 140
On Error Resume Next
Set wrdApp = GetObject(, "Word.Application")
If Err.Number > 0 Then Set wrdApp = CreateObject("Word.Application")
On Error GoTo 0
wrdApp.Visible = True
Set wrdDoc = wrdApp.Documents.Open("C:TPX-" & TP & ".docx")
For i = i To maxRowCount
If Cells(i, 4).Text = TP Then
FindWord = Cells(i, 1).Text
'// Defines selection for Word's find function
wrdDoc.ActiveWindow.Selection.GoTo What:=wdGoToSection, Which:=wdGoToFirst
wrdDoc.SelectAllEditableRanges
iCount = 0
'// Word Find Method Setup Block
With wrdDoc.ActiveWindow.Selection.Find
.Text = FindWord
.Replacement.Text = ""
.Forward = True
.Wrap = 1 ' wdFindContinue (Word constant not defined in Excel)
.Format = False
.MatchCase = True
.MatchWholeWord = True
.MatchWildcards = False
.MatchSoundsLike = False
.MatchAllWordForms = False
Do While wrdDoc.ActiveWindow.Selection.Find.Execute
iCount = iCount + 1
wrdDoc.ActiveWindow.Selection.MoveRight
' MsgBox iCount
Loop
End With
'// Unnecessary storing, I know
result = iCount
Cells(i, 6).Value = result
If result > 1 Then
Cells(i, 7).Value = "YES"
Else
Cells(i, 7).Value = "NO"
End If
Else
TP = Cells(i, 4).Text
FindWord = Cells(i, 1).Value
'// Close and don't save application
wrdApp.Quit SaveChanges:=0 ' wdDoNotSaveChanges (Word constant not defined in Excel)
Set wrdApp = Nothing
Set wrdDoc = Nothing
On Error Resume Next
Set wrdApp = GetObject(, "Word.Application")
If Err.Number > 0 Then Set wrdApp = CreateObject("Word.Application")
On Error GoTo 0
Set wrdDoc = wrdApp.Documents.Open("C:TPX-" & TP & ".docx")
'// Defines selection for Word's find function
wrdDoc.ActiveWindow.Selection.GoTo What:=wdGoToSection, Which:=wdGoToFirst
wrdDoc.SelectAllEditableRanges
iCount = 0
'// Word Find Method Setup Block
With wrdDoc.ActiveWindow.Selection.Find
.Text = FindWord
.Replacement.Text = ""
.Forward = True
.Wrap = 1 ' wdFindContinue (Word constant not defined in Excel)
.Format = False
.MatchCase = True
.MatchWholeWord = True
.MatchWildcards = False
.MatchSoundsLike = False
.MatchAllWordForms = False
Do While wrdDoc.ActiveWindow.Selection.Find.Execute
iCount = iCount + 1
wrdDoc.ActiveWindow.Selection.MoveRight
Loop
End With
'// Unnecessary storing, I know
result = iCount
Cells(i, 6).Value = result
If result > 1 Then
Cells(i, 7).Value = "YES"
Else
Cells(i, 7).Value = "NO"
End If
End If
Next i
End Sub
错误行上的语法似乎正确。您可以:
- 通过摘除debug.print
线以显示文件名表达式
来验证文件名
- 通过手动打开单词,在代码中删除On error
并再次运行。