测试属性名是否存在

7

我遇到了这个错误:

运行时错误 '424',需要对象

当我尝试运行以下代码时出现该错误:

Sub SuperSaveAs()
Set objFSO = CreateObject("Scripting.FileSystemObject")
Dim pathName As String
Dim myFileName As String

If (ActiveDocument.CustomDocumentProperties("_CheckOutSrcUrl").Value = True) Then
    pathName = ActiveDocument.CustomDocumentProperties("_CheckOutSrcUrl").Value
    myFileName = pathName + ActiveWorkbook.Name
        ActiveWorkbook.SaveAs Filename:= _
            myFileName _
            , FileFormat:=xlOpenXMLWorkbookMacroEnabled, CreateBackup:=False
Else
    MsgBox "_CheckOutSrcUrl is missing"
End If

End Sub

这个宏与Excel中的按钮相连接。该宏检查自定义文档属性是否存在。如果自定义文档属性存在,则宏应将文件保存到_CheckOutSrcUrl(SharePoint目录)的值。 我应该如何修复这个错误?


1
Excel没有ActiveDocument - 它是ActiveWorkbook - Rory
2个回答

14

您不能使用上述方法测试属性名称是否存在。有两种明显的方法,以下并非我个人的答案:

  1. 使用循环检查所有属性名称,看看是否找到"_CheckOutSrcUrl"。参见https://answers.microsoft.com/en-us/office/forum/office_2007-word/using-customdocumentproperties-with-vba/91ef15eb-b089-4c9b-a8a7-1685d073fb9f

  2. 使用VBA错误检测来查看属性"_CheckOutSrcUrl"是否存在。参见http://www.vbaexpress.com/forum/showthread.php?15366-Solved-CustomDocumentProperties-Problem

#1 的代码示例片段适用于您的代码 - 最好在一个函数中实现:

Dim propertyExists As Boolean
Dim prop As DocumentProperty
propertyExists = False
For Each prop In ActiveDocument.CustomDocumentProperties
    If prop.Name = "_CheckOutSrcUrl" Then
        propertyExists = True
        Exit For
    End If
Next prop

将 #2 的代码片段示例适应于你的代码:

Dim propertyExists As Boolean
Dim tempObj
On Error Resume Next
Set tempObj = ActiveDocument.CustomDocumentProperties.Item("_CheckOutSrcUrl")
propertyExists = (Err = 0)
On Error Goto 0

2

基于@Cybermike的最初回答:

Function propertyExists(propName) As Boolean

    Dim tempObj
    On Error Resume Next
    Set tempObj = ActiveDocument.CustomDocumentProperties.Item(propName)
    propertyExists = (Err = 0)
    On Error GoTo 0

End Function

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接