在Excel VBA中委派数组

时间:2013-12-20 21:34:34

标签: vba excel-vba excel

如何在Excel VBA中声明代理数组?

我正在审核Excel电子表格,每列需要不同的功能来确定单元格的好坏。每个函数都是相同的类型,

Private Function checkCell(auditCell As Range) As Boolean

如果我可以声明一个Delegate数组,我可以将处理不同checkCell函数的顺序推送到实际审计工作表的函数之外的函数,这可能会成为迭代的嵌套循环我的代表阵列。

甚至在Excel VBA中定义Delegate? VBA编辑器告诉我

1 个答案:

答案 0 :(得分:3)

AFAIK“开箱即用”无法使用。话虽如此,您可以使用WIN32 API调用(来自Delegate)来实现user32.dll功能。

以下是示例代码:

Option Explicit

'-----External Library Declaration which helps call the Proc by Address -----
Private Declare Function CallWindowProc _
                          Lib "user32.dll" Alias "CallWindowProcA" ( _
                              ByVal lpPrevWndFunc As Long, _
                              ByVal hwnd As Long, _
                              ByVal msg As Long, _
                              ByVal wParam As Long, _
                              ByVal lParam As Long) As Long


'-----This is the main function calling upon the proc via pointer -----
Public Sub test_delegate()
    Dim sMessage As String
    Dim nSubAddress    'As Long

    'This message will be passed to our Sub as an argument
    sMessage = InputBox("Please input a short message")
    'Get the address to the sub we are going to call
    nSubAddress = ProcPtr(AddressOf ShowMessage)
    'Do the magic! Function Called via Pointer...
    CallWindowProc nSubAddress, VarPtr(sMessage), 0&, 0&, 0&
End Sub

'-----This is the subroutine we want to call by address-----
Private Sub ShowMessage( _
        msg As String, _
        ByVal nUnused1 As Long, _
        ByVal nUnused2 As Long, _
        ByVal nUnused3 As Long)
'This is the Sub we will call by address
'it only use one argument but we need to pull the others
'from the stack, so they are just declared as Long values
    MsgBox msg
End Sub

'-----This function is used to extract the address of value to long -----
Private Function ProcPtr(ByVal nAddress As Long) As Long
'Just return the address we just got
    ProcPtr = nAddress
End Function

来源: http://unlimitedexcel.blogspot.com/2011/12/pointers-in-vba-huhh-delegates-in-vba.html