首页 > 解决方案 > 在 Excel VBA 中将过程分配给变量

问题描述

1.介绍

我需要像以前在其他语言中那样将过程分配给 Excel VBA 中的变量。稍后将使用这些变量来调用相应的过程。我想避免 4 x 30 程序的案例说明。
不幸的是,我尝试了我能想到的一切并在网上搜索,但没有任何效果。所以我希望有人能注意到它,并且可能会立即看到缺少哪个魔法词。
万一这种编程不适用于 VBA,如果有人能向我确认这一点,我将不胜感激。
我简化了我的代码,以便更好地关注问题,并组成了下面的基本部分。这应该允许重现错误。

提前致谢, 芒蒂

2. 基础设施

电脑:Win7Enterprise-64 SP1、Excel 365 ProPlus-32 (1808)

3.代码

类模块

'in StepClass_Module
Public proc As Variant          'proc = procedure to run  

编程模块

Public step(1) As StepClass_Module      'Declare array of procedures  

Sub main()  
   Set step(0) = New StepClass_Module  
   Set step(1) = New StepClass_Module  

   Set step(0).proc = Import()         'Should allocate corresponding Procedure but runs it => error 13  
   Set step(1).proc = Prepare()        'Should allocate corresponding Procedure but runs it => error 13  

   Run step(0).proc                    'Run corresponding Procedure  
   Run step(1).proc                    'Run corresponding Procedure  
End Sub


Function Import() As Variant  
   Debug.Print ("Import")  
End Function

Function Prepare() As Variant  
   Debug.Print ("Prepare")  
End Function

标签: arraysexcelclassprocedureassign

解决方案


这是更新的代码,因为我想让它运行,现在它可以工作了!大帮助!

类模块 =============

    'in StepClass_Module  
    Public proc As String          'proc = procedure to run  

Programming Module
==================

Public step(1) As StepClass_Module      'Declare array of procedures  

Sub main()  
   Set step(0) = New StepClass_Module  
   Set step(1) = New StepClass_Module  

   step(0).proc = "Import"         'allocate corresponding Procedure  
   step(1).proc = "Prepare"        'allocate corresponding Procedure  

   Run step(0).proc                'Run corresponding Procedure  
   Run step(1).proc                'Run corresponding Procedure  
End Sub  



Sub Import()  
   Debug.Print ("Import")  
End Sub  

Sub Prepare()  
   Debug.Print ("Prepare")  
End Sub  

推荐阅读