【发布时间】:2017-01-20 23:09:36
【问题描述】:
任务: 我的目标是检查是否在 Excel 工作簿的 BuiltInDocumentProperties 集合中设置了值。
放大备注: 我知道某些文档属性项永远不会在 Excel 中显示值,因为它们 属于 ms word 或 ppt 应用程序(例如 item 15 'Number of words',item 25 'Slides' ...)。 另一方面,有些属性在第一次使用时只有偶尔的值:
- 第 10 项:“上次打印时间”
- 第 12 项:“上次保存时间”
当然可以通过错误捕获来做到这一点:
带有错误捕获的示例代码:
Sub test_showDocPropValue()
' Name of built in doc prog
Dim propName As String
' a) Choose builtin doc prop disposing about a set value, such as 'Author', 'Category', ...
' propName = "Category"
' b) Choose builtin doc prop of another ms application
' propName = "Number of pages"
' c) Choose doc prop with occasionally set values
propName = "Last print time"
' Show result
MsgBox propName & " = " & showDocPropValue(propName), vbInformation, "BuiltInDocumentProperties"
End Sub
Function showDocPropValue(ByVal propName As String) As Variant
Dim prop As Object
Dim ret
' Built in Doc Props collection
Set prop = ThisWorkbook.BuiltinDocumentProperties
' Error trapping
On Error Resume Next
ret = prop(propName).Value
If Err.Number <> 0 Then
ret = "(No value set)"
Debug.Print Err.Number & ": " & Err.Description
End If
' Return
showDocPropValue = ret
End Function
我的问题: 出于主要原因,我想知道是否有一种简单的方法来获取 builtinDocumentProperties 值以避免错误捕获
附加提示 只是为了通过在 CUSTOM doc props 中显示没有错误捕获的方法来完成主题,您可以使用以下代码轻松检查此类项目的存在:
Private Function bCDPExists(sCDPName As String) As Boolean
' Purp.: return True|False if custom document property name exists
' Meth.: loop thru CustomDocumentProperties and check for existing sCDPName parameter
' Site: <http://stackoverflow.com/questions/23917977/alternatives-to-public-variables-in-vba/23918236#23918236>
' cf: <https://answers.microsoft.com/en-us/msoffice/forum/msoffice_word-mso_other/using-customdocumentproperties-with-vba/91ef15eb-b089-4c9b-a8a7-1685d073fb9f>
Dim cdp As Variant ' element of CustomDocumentProperties Collection
Dim boo As Boolean ' boolean value showing element exists
For Each cdp In ThisWorkbook.CustomDocumentProperties
If LCase(cdp.Name) = LCase(sCDPName) Then
boo = True ' heureka
Exit For ' exit loop
End If
Next
bCDPExists= boo ' return value to function
End Function
【问题讨论】:
-
顺便说一句,示例性问题。我希望每个人都可以这样问他们!