1
我正尝试在已使用.Find
的另一个循环内使用.Find
函数创建一个循环。我想搜索已保存在数组中的字符串。Excel VBA:嵌套循环中的FindNext
例如,这些是保存在Sheet1中的数组strItem
中的字符串值。
"unit1", "unit2", "unit3"
我想从Sheet2中逐一搜索它们。 Sheet2中看起来是这样的:
unit1
unit2
unit3
unit1.pdf
text1
subject1
subject2
subject3
text2
=========
unit2.pdf
text1
subject1
subject2
subject3
text2
=========
unit3.pdf
text1
subject1
subject2
subject3
text2
=========
搜索"unit1.pdf"
后,我搜索所有细胞低于它“主题”,并获得subject1,2单元格的值,并3.“主题”细胞应在停止搜索下一个包含“====”的单元格。
接下来,我搜索"unit2"
,如果找到像前面一样搜索“主题”单元格。再次,停止在包含“====”的单元格。等等。
在我的代码,我试图做的是字符串“单位”
- 搜索。
- 使用其
.row
作为开始搜索“主题”的范围。 - 返回所有科目,直到单元格包含
"===="
。 这是我的代码的一部分,我不能使用。
代码:
Wb2.Sheets("Sheet2").Activate
With Wb2.Sheets("Sheet2").Range("A1:A1048575")
For Each strItem In arrExcelValues
myStr = strItem & ".pdf"
Set p = .Find(What:=myStr, LookIn:=xlValues, _
LookAt:=xlPart, SearchOrder:=xlByRows, MatchCase:=False)
If Not p Is Nothing Then
firstAddress = p.Address
Do
myStr2 = p.row
strStart = "A" & myStr2
strEnd = "A1048575"
With Wb2.Sheets("Sheet2").Range(strStart, strEnd)
Set p1 = .Find(What:="Subject", LookIn:=xlValues, _
LookAt:=xlPart, SearchOrder:=xlByRows, MatchCase:=False)
If Not p1 Is Nothing Then
firstAddress = p1.Address
Do
myStr2 = myStr2 + 1
If p1.Offset(myStr2, 0).Value = "====" Then
Exit Do
Else
MsgBox p1.Value & strItem
End If
Set p1 = .FindNext(p1)
Loop While Not p1 Is Nothing And p1.Address <> firstAddress
Else
MsgBox "Not found"
End If
End With
Set p = .FindNext(p)
Loop While Not p Is Nothing And p.Address <> firstAddress
Else
MsgBox "Not found"
End If
Next
End With
感谢您提供的信息非常丰富。我真的学到了很多。我已经阅读并研究了您的代码,并将其合并到我的子代。我只是调整了很少,以适应,它完美的作品!我很感激。 :) – Pinked
不用担心,很高兴我可以帮助:) – Wolfie