测试属性名称是否存在

Nic*_*Try 4 excel vba excel-vba

我收到这个错误:

需要运行时错误'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
Run Code Online (Sandbox Code Playgroud)

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

cyb*_*ike 10

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

  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
Run Code Online (Sandbox Code Playgroud)

适用于您的代码的#2片段示例:

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