Vba 测试属性名是否存在

Vba 测试属性名是否存在,vba,excel,Vba,Excel,我得到了这个错误: 需要运行时错误“424”对象 当我尝试运行此代码时: Sub SuperSaveAs() Set objFSO = CreateObject("Scripting.FileSystemObject") Dim pathName As String Dim myFileName As String If (ActiveDocument.CustomDocumentProperties("_CheckOutSrcUrl").Value = True) Then path

我得到了这个错误:

需要运行时错误“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中的按钮连接。宏将检查自定义文档属性是否存在。如果存在自定义文档属性,则宏应将文件保存为
\u CheckOutSrcUrl
(SharePoint目录)的值。
如何修复错误?

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

  • 使用循环检查所有属性名称,并查看是否找到“\u CheckOutSrcUrl”。看

  • 使用VBA错误检测查看属性“\u CheckOutSrcUrl”是否存在。看

  • 适合您的代码的#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
    
    基于@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
    

    Excel没有
    ActiveDocument
    ——它是
    ActiveWorkbook