实现子程序以在宏中重复代码

时间:2019-09-25 15:30:14

标签: excel vba

我想知道有什么方法可以缩短我的当前代码。我在很多宏中运行一个进程,并在考虑子例程。我尝试了几种方法,但无法正常工作。

我几次执行一次搜索:

Sub AddFileToDC()

    '... I am getting oDCSearchConditions from the search, then

    ' Execute the search
    Dim oDCObjectSearchResults As MFilesAPI.ObjectSearchResults
    Set oDCObjectSearchResults = oVault.ObjectSearchOperations.SearchForObjectsByConditions(oDCSearchConditions, MFSearchFlagNone, False)

    ' Get a reference to the existing document collection
    Set oDocumentCollectionOVAP = oVault.ObjectOperations.GetObjectVersionAndProperties(oDCObjectSearchResults.Item(1).ObjVer)

    Set oOldDocumentOVAP = oVault.ObjectOperations.GetObjectVersionAndProperties(oObjectSearchResults.Item(1).ObjVer)

End Sub

在所有其他宏中,我从获得oObjectSearchResults的位置进行另一次搜索。

不是将上面的代码复制到我的所有宏,而是可以执行以下操作:

Sub Code1()

    '... I am getting oSearchConditions from the search, then

        ' Execute the search
        Dim oObjectSearchResults As MFilesAPI.ObjectSearchResults
        Set oObjectSearchResults = oVault.ObjectSearchOperations.SearchForObjectsByConditions(oSearchConditions, MFSearchFlagNone, False)

    AddFileToDC

End Sub

现在在运行Code1时,我收到一条错误消息,提示未定义变量oDCObjectSearchResults,因为它在另一个子AddFileToDC中...

1 个答案:

答案 0 :(得分:1)

在为变量命名后,将命名变量设为全局变量,同时从被调用的宏中删除设置/尺寸:

Public oObjectSearchResults As MFilesAPI.ObjectSearchResults

Sub Code1()

        ' Execute the search
        Set oObjectSearchResults = oVault.ObjectSearchOperations.SearchForObjectsByConditions(oSearchConditions, MFSearchFlagNone, False)

    AddFileToDC

End Sub

Sub AddFileToDC()

    ' Get a reference to the existing document collection
    Set oDocumentCollectionOVAP = oVault.ObjectOperations.GetObjectVersionAndProperties(oDCObjectSearchResults.Item(1).ObjVer)

    Set oOldDocumentOVAP = oVault.ObjectOperations.GetObjectVersionAndProperties(oObjectSearchResults.Item(1).ObjVer)

End Sub