需求
客户的PPT文字要转成word,且格式不变。
思路
都知道,PPT是文本框组成的,要转成word有两种方法。
1.PPT先转成PDF,然后PDF再转成word
2.PPT文本框一个一个复制到word
我这采用第二种方法。那就是需要使用ppt-vba生成word
- (PPT-VBA)逐序遍历每一页幻灯片的文本框 - 对一个幻灯片页文本框操作时,复制。 - 粘贴到一个新建的word文档里 - 返回到PPT,再复制(激活PPT) - 再粘贴到上个的word文档里(激活word) |
可以看到,需要从:ppt激活到word,word激活到PPT
方法
方法一:AppActivate ("Word")
此方法在VBA中激活程序时,用其他网友的话说,不稳定不靠谱
方法二:用VBA使用Window API来完成
Option Compare Text '声明比较字符串数据时要使用的默认比较方法按TEXT比较。
' Window API 引用声明
Private Declare PtrSafe Function BringWindowToTop Lib "user32" (ByVal hwnd As Long) As Long
Private Declare PtrSafe Function FindWindow Lib "user32" Alias "FindWindowA" ( _
ByVal lpClassName As String, _
ByVal lpWindowName As String) As Long
Private Declare PtrSafe Function SetFocus Lib "user32" (ByVal hwnd As Long) As Long
Private Sub test20240305_【程序】切换程序(windowName As String)
Dim Res As Long
Dim XLHWnd As Long, XLHWndEx As Long
Const MyCLASS = "OpusApp" 'EXCEL:XLMAIN;
'FindWindow函数有两个参数,第一个是要找的窗口的类,第二个是要找的窗口的标题。
'在搜索的时候不一定两者都知道,但至少要知道其中的一个。
'有的窗口的标题是比较容易得到的,如"计算器",所以搜索时应使用标题进行搜索。
'但有的软件的标题不是固定的,如"记事本",如果打开的文件不同,窗口标题也不同,
'这时使用窗口类搜索就比较方便。
XLHWnd = FindWindow(lpClassName:=MyCLASS, lpWindowName:=(windowName + " - Word"))
If XLHWnd > 0 Then
Res = BringWindowToTop(hwnd:=XLHWnd) '设置活动窗口XLHWnd
If Res = 0 Then
MsgBox "置顶激活错误,错误代码: " & CStr(Err.LastDllError)
Else
SetFocus hwnd:=XLHWnd
Debug.Print windowName & "打开成功"
End If
Else
Debug.Print windowName & "打开失败"
End If
End Sub
Sub test20240303_【弹出框】()
For Each oneD In Documents
Debug.Print oneD.Windows(1).Caption
test20240305_【程序】切换程序 oneD.Windows(1).Caption
Next
End Sub
代码如上,其实使用api激活程序网络上很多相关博客,我的这个也是抄的。
但是,激活特定word文档时,有一个点要注意:
lpWindowName:=(windowName + " - Word")
- 如果激活文档假如为 "翻译YKBtM.doc",那么文档名称后面加 [空格]-[空格]Word,才能正确激活;
- 如果激活文档为兼容模式 的"翻译YKBtM.doc" ,那么兼容模式那几个字也要加;
其实还有一个简便方法:
方法三:
Set ws = CreateObject("WScript.Shell")
Debug.Print Documents(1).name
ws.AppActivate Documents(1).name
Documents(1).name 比如是:"翻译YKBtM.doc"
总结
使用api激活word文档时,有一个点要注意:文档名称后面加 [空格]-[空格]Word,才能正确激活