excel - 通过 excel VBA 打开 PowerPoint
问题描述
我想通过excel VBA打开我的PowerPoint文件,只提供文件的扩展名(.pptx)。我看过一些代码,但它们需要提供文件的全名。是否有可能做到这一点?我的文件夹中只保留一个 PowerPoint 文件。
解决方案
你可以这样做:
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
推荐阅读
- java - 如何避免 Gradle Exec 在 Windows 上的命令行中扩展通配符?
- nuxt.js - ReferenceError: $nuxt 未定义
- java - 在java上使用贝塞尔曲线创建动画
- android - 颤动如何检查在启动画面中是否授予了位置权限
- r - 根据第二个数据帧 R 中的值将数据帧中的单元格转换为 0
- android - 有没有办法让 Firebase Crashlytics 在远程服务中工作?
- date - 更改日期类型时,我在 Power BI 中遇到错误
- makefile - GNU Make:如何计算可以生成多个模块的代码生成器的依赖关系?
- ffmpeg - 对视频中的 PAR(像素长宽比)感到困惑
- java - 如何使用 mockito 在服务测试中模拟工厂方法