2017-01-03 102 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

相關問題