[办公] 检索pdf文件:如果文件名是前8位为数字和第9位为英文字母的PDF文件名

JUMU实名认证 发表于 2025-09-30 13:06 | 显示全部楼层 | 复制链接分享      上一主题  翻页  下一主题
编写excel VBA程序:检索当前文件夹“C:\Users\ZHU-222\Desktop\图纸及清单”中的所有文件,包括子文件夹。检索pdf文件。如果文件名是前8位为数字和第9位为英文字母的PDF文件名。将这些文件名暂存。然后在当前excel表D列和F列第三行开始依次填入文件名中的前8位数字,同时在对应的E列和G列填入第9位字母。

  1. Sub ExtractPDFNames()
  2.     Dim fso As Object
  3.     Dim folderPath As String
  4.     Dim mainFolder As Object
  5.     Dim subFolder As Object
  6.     Dim file As Object
  7.     Dim rowNum As Long
  8.     Dim regex As Object
  9.     Dim matches As Object
  10.    
  11.     ' 设置目标文件夹路径
  12.     folderPath = "C:\Users\ZHU-222\Desktop\图纸及清单"
  13.    
  14.     ' 创建文件系统对象
  15.     Set fso = CreateObject("Scripting.FileSystemObject")
  16.     Set mainFolder = fso.GetFolder(folderPath)
  17.    
  18.     ' 创建正则表达式对象
  19.     Set regex = CreateObject("VBScript.RegExp")
  20.     regex.Pattern = "^(\d{8})([A-Za-z])\.pdf$"
  21.     regex.IgnoreCase = True
  22.    
  23.     rowNum = 3 ' 从第3行开始填充
  24.    
  25.     ' 遍历主文件夹及子文件夹
  26.     Call TraverseFolders(mainFolder, regex, rowNum)
  27.    
  28.     MsgBox "处理完成,共处理 " & (rowNum - 3) & " 个文件", vbInformation
  29. End Sub

  30. Sub TraverseFolders(currentFolder As Object, regex As Object, ByRef rowNum As Long)
  31.     Dim subFolder As Object
  32.     Dim file As Object
  33.    
  34.     ' 遍历当前文件夹中的文件
  35.     For Each file In currentFolder.Files
  36.         If LCase(Right(file.Name, 4)) = ".pdf" Then
  37.             Dim matches As Object
  38.             If regex.Test(file.Name) Then
  39.                 Set matches = regex.Execute(file.Name)
  40.                 Dim numPart As String
  41.                 Dim letterPart As String
  42.                
  43.                 numPart = matches(0).SubMatches(0)
  44.                 letterPart = UCase(matches(0).SubMatches(1))
  45.                
  46.                 ' 写入Excel单元格
  47.                 With ThisWorkbook.ActiveSheet
  48.                     .Cells(rowNum, 4).Value = numPart   ' D列
  49.                     .Cells(rowNum, 5).Value = letterPart ' E列
  50.                     .Cells(rowNum, 6).Value = numPart   ' F列
  51.                     .Cells(rowNum, 7).Value = letterPart ' G列
  52.                 End With
  53.                
  54.                 rowNum = rowNum + 1
  55.             End If
  56.         End If
  57.     Next
  58.    
  59.     ' 递归遍历子文件夹
  60.     For Each subFolder In currentFolder.SubFolders
  61.         TraverseFolders subFolder, regex, rowNum
  62.     Next
  63. End Sub
复制代码


  距米网  

找到您想要的设计

工程师、学生在线交流学习平台
关注我们

手机版- 距米网 |苏公网安备32041102000587号

©2017-2025 苏ICP备18040927号-1