如何从即时 window 调用 Excel 自定义功能区按钮?

How to call an Excel custom ribbon button from the immediate window?

有一个程序 c1(),看起来像这样:

Sub c1(control As IRibbonControl)
    Debug.Print "foo"
End Sub

它正在从功能区成功调用,代码正确onAction="c1"/>

问题: 如何从立即 window 调用相同的过程(用于调试目的)?它要求一个参数,我不知道如何提供:

试试这个解决方法

Sub c1(control As IRibbonControl)
    call c1_subroutine
End Sub

Sub c1_subroutine()
    Debug.Print "foo"
End Sub

并立即 window 调用 c1_subroutine

如果您在 c1 中的代码不依赖于 control 您可以使用

c1 nothing

立即window。


你可以做什么,例如:

Private lobjRibbon As IRibbonUI

Public Declare PtrSafe Sub CopyMemory Lib "kernel32.dll" Alias "RtlMoveMemory" ( _
    ByRef Destination As Any, ByRef source As Any, ByVal length As Long)

Public Sub Ribbon_CallbackOnLoad(ByRef probjRibbon As IRibbonUI)
    Set lobjRibbon = probjRibbon
    Range("A1").Value = CStr(ObjPtr(lobjRibbon)) 'write the pointer to a cell to save it even if VBA stops
End Sub

使用 Ribbon_CallbackOnLoad 将加载时的功能区设置为变量 lobjRibbon 或保存它的指针(以防 VBA 完全结束)。

您可以使用

Function GetRibbon(ByVal lRibbonPointer As LongPtr) As Object
    Dim objRibbon As Object
    Call CopyMemory(objRibbon, lRibbonPointer, LenB(lRibbonPointer))
    Set GetRibbon = objRibbon
    Set objRibbon = Nothing
End Function

从其保存的指针中取回 ribbob 对象,例如

Sub RefreshRibbon(Optional ControlID As String = vbNullString)
    If lobjRibbon Is Nothing Then
        Set lobjRibbon = GetRibbon(CLngPtr(Range("A1").Value))

        If ControlID = vbNullString Then
            lobjRibbon.Invalidate
        Else
            lobjRibbon.InvalidateControl ControlID
        End If
    Else
        If ControlID = vbNullString Then
            lobjRibbon.Invalidate
        Else
            lobjRibbon.InvalidateControl ControlID
        End If
    End If
End Sub