【问题标题】:Assign Procedure to Variable in Excel VBA在 Excel VBA 中将过程分配给变量
【发布时间】:2019-08-11 08:55:40
【问题描述】:

1.简介

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

提前谢谢你,芒蒂

2。基础设施

PC: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

【问题讨论】:

  • 只需将过程名称作为字符串传递。这就是Run 所期望的。
  • 嗨,Rony,非常感谢您为我节省了这么多时间。我希望这是一个小话题,但从未考虑过“奔跑”。我只为遇到同样问题的人修改了我的代码。我似乎无法在评论中执行此操作。我会尝试一个答案。

标签: arrays excel class procedure assign


【解决方案1】:

考虑以下模型:

Sub main()
    Dim s As String
    s = "inputt,makereport,outputt"
    arr = Split(s, ",")

    For Each a In arr
        Run a
    Next a
End Sub

Sub inputt()
    MsgBox "input"
End Sub

Sub makereport()
    MsgBox "reporting"
End Sub

Sub outputt()
    MsgBox "dun"
End Sub

【讨论】:

  • 嗨,Gary,现在了解您的代码,对我来说主要信息是,Run 必须与过程名称一起用作我不知道(知道)的字符串。这个改变解决了我的问题。非常感谢您的努力。
【解决方案2】:

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

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

    '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  

【讨论】:

    猜你喜欢
    • 2021-09-19
    • 2013-07-25
    • 2020-01-01
    • 2013-03-27
    • 1970-01-01
    • 1970-01-01
    • 2015-12-06
    • 2012-07-21
    • 1970-01-01
    相关资源
    最近更新 更多