excel - 如何在文件中查找字符串,关闭文件并循环到文件夹中的下一个文件?
问题描述
我想遍历文件夹中的所有 .xlsx 文件以查找字符串。
如果找到,将文件名、单元格地址、单元格中的文本写入文件,然后关闭文件并移至文件夹中的下一个文件。
该文件未格式化并已合并单元格。
下面的代码部分工作。问题是,如果在文件中找不到该字符串,则该文件保持打开状态,并且不会循环到下一个文件。
Sub StringSearch()
Dim lRow As Long
Dim oFile As Object
Dim oFiles As Object
Dim oFolder As Object
Dim rFound As Range
Dim rSearch As Range
Dim strFirstAddress As String
Dim strSearch As String
Dim vPath As Variant
Dim wbk As Workbook
Dim wks As Worksheet
Dim wOut As Worksheet
Application.ScreenUpdating = False
vPath = ThisWorkbook.Worksheets("Sheet1").Range("B3").Value
strSearch = ThisWorkbook.Worksheets("Sheet1").Range("D3").Value
With CreateObject("Shell.Application")
Set oFolder = .Namespace(vPath)
If oFolder Is Nothing Then
MsgBox "The folder """ & vPath & """ was Not Found.", vbExclamation
Exit Sub
End If
Set oFiles = oFolder.Items
' // Open only xls, xlsx, and xlsm workbooks
oFiles.Filter 64, "*.xls;*.xlsx;*.xlsm"
End With
Set wOut = Worksheets.Add
lRow = 1
' // Add row headers to the new worksheet.
wOut.Range("A1:D1").Value = Array("Workbook", "Worksheet", "Cell", "Text in Cell")
For Each oFile In oFiles
Set wbk = Workbooks.Open _
(Filename:=oFile.Path, _
UpdateLinks:=0, _
ReadOnly:=True, _
AddToMRU:=False)
For Each wks In wbk.Worksheets
Set rSearch = wks.UsedRange
Set rFound = rSearch.Find(strSearch)
If rFound Is Nothing Then Exit Sub
strFirstAddress = rFound.Address
Do
lRow = lRow + 1
wOut.Cells(lRow, "A").Resize(1, 4).Value = Array(wbk.Name, wks.Name, rFound.Address, Split(rFound.Value, "P")(0))
Set rFound = wks.Cells.FindNext(rFound)
If rFound Is Nothing Then Exit Do
If rFound.Address = strFirstAddress Then Exit Do
Loop
Next wks
wOut.Columns("A:D").EntireColumn.AutoFit
wbk.Close SaveChanges:=False
Next oFile
MsgBox "Done"
Application.ScreenUpdating = True
End Sub
解决方案
推荐阅读
- python - 将两个矩阵相加(使用方法,不使用 numpy)
- go - 如何从 GO 中的 arango DB 中删除一个顶点并自动删除边缘?
- vbscript - SAP 脚本录制和回放 - 累积数据
- vega - timeFormat vega 格式秒
- proxy - 有哪些网站可以绕过公司防火墙并查看被阻止的网站?(不是代理)
- bitbucket-pipelines - bitbucket-pipelines 中的“pynvml.NVMLError_LibraryNotFound:未找到 NVML 共享库”
- python - 计算金融资产每日收益的方法:df.pct_change() 是计算任何金融资产的正确程序吗?
- npm - 如何使用 Vite 向用户显示 package.json 中的当前应用版本?
- python - 在python中使用for循环作为包含str和int的列表的过滤器
- gitlab - 如何在 gitlab ci 中使用另一个变量