2017-01-03 104 views
0

'在Excel-VBA中,有什么办法可以获得进程名称 '我正在运行?例如,在Excel VBA中,我是 '执行一个子mysub()。在这个子文件中,我希望 '将子文件名“mysub”缓存到变量 中,以备稍后使用。如何实现?在Excel-VBA中,有没有办法让程序名称'我正在运行?

Sub mysub() 

    getmysubname = howtoget 'this is my variable to catch the sub name 

    Debug.Print getmysubname 'sub name is printed in debug window 

    End Sub 

“请提供要做到这一点

回答

2

答案是否定的方法。有没有通用的方法,但是使用则名为像你所在的子变量。

public CurrentSub as string 
sub mysub() 
    CurrentSub ="mysub" '  do as you wish after 
end sub 
+0

我知道这种方法,但我想要这样的东西,如果可用或可能的话; myvar = ActiveWorkbook.VBProject.CurrentSub.name –

1

有一种方式来获得VB项目模块的Sub是,如果你使用一个变量(或常量)以保存您的Sub名称。

请参见下面的代码:

Option Explicit 

Sub mySub() 

Const PROC_NAME = "mySub" 

Dim VBProj As VBIDE.VBProject 
Dim VBComp As VBIDE.VBComponent 
Dim CodeMod As VBIDE.CodeModule 
Dim i As Long 
Dim ModuleName As String 

Set VBProj = ActiveWorkbook.VBProject 

' loop through all modules, worksheets and other objects in VB Project 
For Each VBComp In VBProj.VBComponents 
    Set CodeMod = VBComp.CodeModule 

    ' loop through all code line inside current module 
    For i = 1 To CodeMod.CountOfLines 
     If Len(CodeMod.Lines(i, 1)) > 0 Then 
      ' if the name of current sub is found within the current code line 
      If InStr(CodeMod.Lines(i, 1), PROC_NAME) > 0 Then 
       ModuleName = CodeMod.Name '<-- get the current Module name 
       MsgBox "Sub " & PROC_NAME & " found in " & ModuleName & " module" 
       Exit Sub 
      End If 
     End If 
    Next i 
Next VBComp 

End Sub 

为了访问VB项目模块,需要遵循以下两个步骤:

步骤1:添加“信托访问VBA项目对象模型“,转至开发者 >>宏安全 >>然后将V添加到信任访问VBA项目对象模型

enter image description here

步骤2:添加引用您的VB项目中,添加 “的Microsoft Visual Basic应用程序扩展5.3

enter image description here

就是这样,你就可以搏一搏 !

+0

但是(a)返回模块名称,而不是子名称(即OP要获取值“mySub”,而不是“Module1”或其他),以及b)它将(如果我正确读取)返回可能位于完全不同模块中的“PROC_NAME”的第一个匹配项(例如,调用子程序的位置)。 – YowE3K

+0

@YowE3K我知道,我写了目前我能做的事情,还在想如何让我进来。但仍然,你必须承认它仍然很好(比上面的答案更好) –

+1

我会承认这是**很好** - 但完全脱离主题 - 哈哈。 (我一直希望有一种方法可以访问VBA中的堆栈跟踪 - 如果你找到了一种方法,你将成为第一个这样做的人。) – YowE3K

相关问题