【问题标题】:Test whether a property name exists测试一个属性名是否存在
【发布时间】:2019-06-03 20:53:32
【问题描述】:

我收到此错误:

需要运行时错误“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 目录)。 我该如何解决这个错误?

【问题讨论】:

  • Excel 没有ActiveDocument - 它是ActiveWorkbook

标签: vba excel


【解决方案1】:

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

  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 的 sn-p 示例适用于您的代码 - 最好在函数中:

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 的 sn-p 示例适用于您的代码:

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

【讨论】:

    【解决方案2】:

    基于@Cyber​​mike:

    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
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-02-07
      • 2012-04-24
      • 2011-06-28
      • 2020-05-04
      相关资源
      最近更新 更多