遍历文件夹中的文件,排除最后一个文件

问题描述 投票:0回答:2

我有一个文件夹,其结构为充满幻灯片的子文件夹和这些子文件夹之外的一个幻灯片,有点像这样:

[main folder]
 |-[subfolder 1]
   |-ppt A
 |-[subfolder 2]
   |-ppt B
 |-ppt file to exclude

我的目标是循环遍历这些子文件夹,对子文件夹内的powerpoints进行操作,忽略最后的ppt。我不能硬编码 ppt 的名称,因为名称每周都会更新,标题中有新日期。这可以在不对文件名进行硬编码的情况下完成吗?

在简单测试的同时,我尝试使用 do-while 循环并对名称进行硬编码,但这似乎不起作用。事实上,我认为它最终运行了一个无限循环并使我的 PPT 崩溃:

  Dim File
    For Each File In Folder.Files
        Debug.Print File.path
        
        Do While File <> "hardcoded file name"
            If Right(File, 5) Like ".ppt*" Then
                Set objPresentation = Presentations.Open(File, msoFalse, msoFalse, msoFalse)
                For i = 1 To 1
                    objPresentation.Slides.Item(1).Copy
                    Presentations.Item(1).Slides.Paste
                    Presentations.Item(1).Slides.Item(Presentations.Item(1).Slides.Count).Design = _
                        objPresentation.Slides.Item(1).Design
                    ActivePresentation.Slides(ActiveWindow.View.Slide.SlideIndex).Shapes("Rectangle 2").Delete
                 Next i
                 objPresentation.Close
            End If
        Loop
    Next
    
End Sub

我考虑过使用 case 语句,但不确定将它放在哪里。即使我让它工作,我也不确定如果文件名没有被硬编码它是否仍然可以工作。

vba powerpoint
2个回答
0
投票

要识别开始文件夹中的最后一个文件,您可以使用文件的属性

count

Dim counter As Long
counter = folder.Files.Count
   
For Each file In folder.Files
  counter = counter - 1
  If counter = 0 Then Debug.Print "Last one"
  Debug.Print file.Path
Next file 

要搜索子文件夹,请参阅其他答案,例如here


0
投票

如果你只对子文件夹中的文件感兴趣,那么像这样的东西只会给你那些路径:

Sub Tester()
    Dim f As Object, sf As Object, fl As Object
    
    Set f = CreateObject("Scripting.Filesystemobject").getfolder("C:\Temp\VBA")
    'only check subfolders
    For Each sf In f.subfolders
        Debug.Print sf.Name
        'loop files in subfolder
        For Each f In sf.Files
            If LCase(f.Name) Like "*.ppt*" Then
                Debug.Print , f.Path
            End If
        Next f
    Next sf
End Sub
© www.soinside.com 2019 - 2024. All rights reserved.