从另一个workwook或Add-in卸载Userform

时间:2018-06-18 15:00:07

标签: excel vba excel-vba

我正在尝试运行一些通用代码来从加载项卸载UserForm。以下代码存储在添加的代码中。如何检查用户的特定工作簿?

我一直在玩VBProject.VBComponents,但没有快乐。

Function CheckUnloadForm(ByVal UserFormName As String) As Boolean
Dim objUserForm As Object

CheckUnloadForm = False

For Each objUserForm In VBA.UserForms
  If objUserForm.Name = UserFormName Then
    CheckUnloadForm = True
    Exit For
  End If
Next objUserForm

End Function

1 个答案:

答案 0 :(得分:0)

这可以使用您提到的Visual Basic Extensibility库来完成。在Test过程中,我们循环开放的Workbooks集合,对于每个工作簿,我们循环VBComponents。如果有一个与formName参数匹配的组件,那么我们会将一些代码注入到 工作簿中,该工作簿将Unload.Hide表单,最后我们删除了注入的代码模块。

NB 只有在vbModeless显示表单时才能执行此操作。

在加载项中,使用以下代码创建标准模块:

Option Explicit
Public compName As String
Public procName As String

Sub Test()
Dim wb As Workbook
Dim formName As String
Dim f As Object
formName = "UserForm1"
Dim VBC As Object ' UserForm VBComponent

For Each wb In Workbooks
    For Each VBC In wb.VBProject.VBComponents
        '## If any component matches this name: 
        If VBC.Name = formName Then
            '## Inject some code into wb that will hide/unload the form
            AddCodeToHideUserForm wb, formName
            DoEvents
            '## Call on the Sub that we just injected
            Run procName
            '## Finally, remove the module that we injected into wb.
            RemoveInjectedCode wb, formName
        End If
    Next
Next

End Sub
Sub RemoveInjectedCode(wb As Workbook, formName As String)
Dim cm As VBComponent
On Error Resume Next
Set cm = wb.VBProject.VBComponents(compName)
wb.VBProject.VBComponents.Remove cm

End Sub
Sub AddCodeToHideUserForm(wb As Workbook, formName As String, Optional hideInsteadOfUnload As Boolean = False)
Dim code As String
Dim cm As VBComponent
code = "Public Sub hide" & formName & "()" & vbNewLine
code = code & " On Error Resume Next" & vbNewLine
If hideInsteadOfUnload Then
    code = code & formName & ".Hide" & vbNewLine
Else
    code = code & " Unload " & formName & vbNewLine
End If
code = code & "End Sub"
Set cm = wb.VBProject.VBComponents.Add(vbext_ct_StdModule)
DoEvents
cm.CodeModule.AddFromString (code)
cm.Name = "Hide" & formName
DoEvents
compName = cm.Name
procName = "'" & wb.Name & "'!" & compName & ".hide" & formName

End Sub