分享

VBA遍历文件夹下文件文件实用源码

 hdzgx 2019-11-09
  1. ‘批量遍历文件夹下某类文件,并统计编号
  2. Sub OpenAndClose()
  3. Dim MyFile As String
  4. Dim s As String
  5. Dim count As Integer
  6. MyFile = Dir("d:\data\" & "*.csv")
  7. '读入文件夹中第一个.xlsx文件
  8. count = count + 1 '记录文件的个数
  9. s = s & count & "、" & MyFile
  10. Do While MyFile <> " "
  11. MyFile = Dir '第二次读入的时候不用写参数
  12. If MyFile = "" Then
  13. Exit Do '当myfile为空时候说明已经遍历完了,推出do,否则要重新运行一遍
  14. End If
  15. count = count + 1
  16. If count Mod 2 <> 1 Then
  17. s = s & vbTab & count & "、" & MyFile
  18. Else
  19. s = s & vbCrLf & count & "、" & MyFile
  20. End If
  21. Loop
  22. Debug.Print s
  23. End Sub
  24. ‘遍历每个文件,并且修改文件,先将文件的名字存在数组中,然后通过数组遍历打开每个文件,修改,再关闭文件~
  25. Sub OpenCloseArray()
  26. Dim MyFile As String
  27. Dim Arr(100) As String
  28. Dim count As Integer
  29. MyFile = Dir("D:\data\data2\" & "*.xlsx")
  30. count = count + 1
  31. Arr(count) = MyFile
  32. Do While MyFile <> ""
  33. MyFile = Dir
  34. If MyFile = "" Then
  35. Exit Do
  36. End If
  37. count = count + 1
  38. Arr(count) = MyFile '将文件的名字存在数组中
  39. Loop
  40. For i = 1 To count
  41. Workbooks.Open Filename:="d:\data\data2\" & Arr(i) '循环打开Excel文件
  42. Sheet1.Cells(2, 2) = "alex_bn_lee" '修改打开文件的内容
  43. ActiveWorkbook.Close savechanges = True '关闭打开的文件
  44. Next
  45. ‘要是想要修改每个工作簿的内容可以这样遍历一下,显示将文件夹中的工作簿的名字存到’一个字符串数组中,然后在用For...Next语句遍历
  46. ‘遍历某个文件夹中的所有文件(*.*)
  47. ’注意:遍历的时候,顺序完全是按照文件名的顺序排的,而不是按照文件夹中文件的顺序~
  48. Sub dlkfjdl()
  49. Dim MyFile As String
  50. Dim count As Integer
  51. count = 1
  52. MyFile = Dir("d:\data\*.*")
  53. Debug.Print "1、" & MyFile
  54. Do While MyFile <> ""
  55. count = count + 1
  56. MyFile = Dir
  57. If MyFile = "" Then Exit Do
  58. Debug.Print count & "、" & MyFile
  59. Loop
  60. End Sub


    本站是提供个人知识管理的网络存储空间,所有内容均由用户发布,不代表本站观点。请注意甄别内容中的联系方式、诱导购买等信息,谨防诈骗。如发现有害或侵权内容,请点击一键举报。
    转藏 分享 献花(0

    0条评论

    发表

    请遵守用户 评论公约

    类似文章 更多