首页 > 解决方案 > 通过 excel VBA 打开 PowerPoint

问题描述

我想通过excel VBA打开我的PowerPoint文件,只提供文件的扩展名(.pptx)。我看过一些代码,但它们需要提供文件的全名。是否有可能做到这一点?我的文件夹中只保留一个 PowerPoint 文件。

标签: excelvbapowerpoint

解决方案


你可以这样做:

Sub Open_PPT()

    Dim PPTpath As String
    Dim PPTname As String

    Dim ThisExtension As String
    Dim temp As Variant

    temp = Split(ThisWorkbook.Name, ".")
    ThisExtension = temp(UBound(temp))

    PPTpath = Replace(ThisWorkbook.FullName, ThisExtension, "pptx")
    PPTname = Replace(ThisWorkbook.Name, ThisExtension, "pptx")

    Dim PPT As Object, PPPres As Object
    Set PPT = CreateObject("PowerPoint.Application")
    PPT.Visible = True

    PPT.Presentations.Open FileName:=PPTpath
    Set PPPres = PPT.Presentations(PPTname)
    'open PPT

    PPPres.Slides(1).Select
End Sub

我取工作簿的名称并拆分为“。” 并找到生成数组的最后一个元素 - 可能是“xlsx”。然后将其替换为“pptx”,以便我们现在拥有完整的路径,例如:

"C:\Users\name\Documents\Excel_name.pptx"

和“Excel_name.pptx”这样的文件名然后我们可以创建一个PPT应用程序对象并打开文件(我假设它存在,否则你需要打开一个新的空白PPT并相应地保存)

如果您的问题更像是“我可以在与当前文件夹(保存 Excel 的位置)相同的文件夹中找到具有任何名称的 .pptx 文件”那么您正在寻找类似的内容:

Sub Find_and_open_PPT()

    On Error Resume Next

    Dim FSO As Object, fld As Object
    Dim fileExtn As String
    Dim PPTpath As String
    Dim PPTname As String

    fileExtn = ".pptx"

    Set FSO = CreateObject("Scripting.FileSystemObject")
    Set fsoFolder = FSO.GetFolder(ThisWorkbook.Path)

    For Each fsoFile In fsoFolder.Files 'check the files in the parent folder
        If Err.Number > 0 Then
            'MsgBox "error handling file, likely due to permission"
            Err.Clear
        End If
        If Right(fsoFile, Len(fileExtn)) = fileExtn Then
            'PPT found
            PPTpath = fsoFile
            PPTname = fsoFile.Name
            Exit For
        End If
    Next        

    Dim PPT As Object, PPPres As Object
    Set PPT = CreateObject("PowerPoint.Application")
    PPT.Visible = True

    PPT.Presentations.Open FileName:=PPTpath
    Set PPPres = PPT.Presentations(PPTname)
    'open PPT

    PPPres.Slides(1).Select        

End Sub

您还可以修改它以准确找到您正在寻找的文件名,甚至是一个 unix 文件匹配,例如:

if fsoFile.Name like "example*.ppt*" then

目前,一旦您找到扩展名为“.pptx”的文件,代码就会停止查找:

If Right(fsoFile, Len(fileExtn)) = fileExtn Then

推荐阅读