如何在PowerPoint VBA中存储与检索用户窗体的控件值?
PowerPoint保存用户窗体控件属性的正确实现
原代码的问题
- PPT中不存在
DocumentBeforeClose事件,对应正确事件为PresentationBeforeClose,且必须写在ThisPresentation模块内 - 直接调用
CustomDocumentProperties.Add会触发报错:若自定义属性已存在,重复添加会引发运行时错误 - 若用户窗体已关闭,
UserForm1.TextBox1.Value可能无法正常读取
修正后的代码
在ThisPresentation模块中插入以下代码:
Private Sub PresentationBeforeClose(ByVal Pres As Presentation, Cancel As Boolean) Dim prop As DocumentProperty Dim textBoxValue As String ' 先获取文本框值(确保窗体未提前释放) If UserForm1.Visible Then textBoxValue = UserForm1.TextBox1.Value Else ' 若窗体已关闭,需提前在窗体关闭事件中把值存入模块级变量,示例为Module1中的gTextBoxValue textBoxValue = Module1.gTextBoxValue End If ' 检查自定义属性是否已存在 On Error Resume Next Set prop = Pres.CustomDocumentProperties("MyTextBoxValue") On Error GoTo 0 If prop Is Nothing Then ' 属性不存在则添加 Pres.CustomDocumentProperties.Add _ Name:="MyTextBoxValue", _ LinkToContent:=False, _ Type:=msoPropertyTypeString, _ Value:=textBoxValue Else ' 属性已存在则更新值 prop.Value = textBoxValue End If End Sub
补充说明
- 若用户窗体可能在关闭演示文稿前就被关闭,建议在窗体的
Terminate事件中把控件值保存到标准模块的公共变量中:
标准模块(Module1)中声明:Public gTextBoxValue As String
用户窗体代码:Private Sub UserForm_Terminate() gTextBoxValue = Me.TextBox1.Value End Sub - 下次打开演示文稿时,可通过
ActivePresentation.CustomDocumentProperties("MyTextBoxValue").Value读取保存的值,再赋值给用户窗体控件
内容的提问来源于stack exchange,提问作者Shawn
相关产品推荐
相关产品推荐

