返回当前代码模块名称
我有一些现有的错误记录代码,可以写入。遇到错误时的日期、时间和错误描述的日志文件。我想添加的一件事(不硬编码)是触发错误消息的代码mod的名称。例如,如果在CommandButton1_Click事件中发生错误,我希望代码自动神奇地“知道”错误发生在哪里。我假设我需要添加VBA Extenity的引用,但从那里我有NO IDEA走哪条路。
**** Hidden Message ***** 听起来您需要的是GetModuleFileName
API指南(可从www.allapi.net免费获得)有一个示例,说明如何使用VB(a)中的GetModuleFileName和许多其他WIN32 API函数
AllAPI还提供了一个名为ApiViewer的便捷程序,可供免费下载。它将为您创建函数、常量和类型声明,并将它们放在剪贴板上,这样您就可以将它们粘贴到应用程序中。
嗯。转念一想,我想我误解了你的问题。 嗯....是的。。。。
不完全
是我想要的。
以下是我现在在一些Access DB新闻组上找到
的代码:
Sub WhatProcs()
Dim oProj As VBProject
Dim oComp As VBComponent
Dim oMod As CodeModule
Dim nLine As Long
Dim strProcName As String
Set oProj = ThisDrawing.Application.VBE.ActiveVBProject
For Each oComp In oProj.VBComponents
' Confusingly, each oComp corresponds to a "Module"
' as shown in the Project Explorer. Then oMod
' represents the code itself, which has no name.
Set oMod = oComp.CodeModule
Debug.Print oComp.Name
' Step past the declarations at the top
nLine = oMod.CountOfDeclarationLines + 1
Do While nLine < oMod.CountOfLines
' Get the name of the procedure enclosing the line
strProcName = oMod.ProcOfLine(nLine, vbext_pk_Proc)
Debug.Print vbTab & strProcName
' Add this procedure's line count to the current line
' to find the next procedure (or the end of the module)
nLine = nLine + oMod.ProcCountLines(strProcName, vbext_pk_Proc)
Loop
Next oComp
Set oMod = Nothing
Set oComp = Nothing
Set oProj = Nothing
End Sub
Public Sub Test1()
MsgBox "This is a test"
End Sub
Public Sub Test2()
MsgBox "This is also test"
End Sub
以前的代码在放入新的DVB时,会吐出以下内容:
ThisDrawing
Module1
WhatProcs
Test1
Test2
我希望它只吐出WhatProcs,因为这是运行代码的过程。 如果我从Test1子中运行了一些代码,我希望它返回Test1(上帝,我希望这有意义,因为我不确定我是否可以再遵循它)。
回想起来,也许“模块”这个词用错了。 可能应该使用“程序”??相反?? 我不知道。。。我精疲力竭。 不能直截了当地思考。 咖啡因没有帮助。 激励 f-a-d-i-n-g 快速。 试试这个,它要求你对每个潜艇进行错误控制,这根本不是问题。
Randall Rath编写了一个自动错误处理程序函数,可以为您编写行,非常好。
Sub ActiveCode()
Dim oIDE As VBE
Dim oPane As CodePane
Dim oMod As CodeModule
Dim sProc As String
Dim lngSC As Long 'Start column
Dim lngEC As Long 'End Column
Dim lngSL As Long 'Start Line
Dim lngEL As Long 'End Line
Dim sActiveProject As String
Dim sActModule As String
Set oIDE = Application.VBE
sActiveProject = oIDE.ActiveVBProject.Name
Set oPane = oIDE.ActiveCodePane
Set oMod = oPane.CodeModule
sActModule = oPane.CodeModule.Name
oPane.GetSelection lngSL, lngSC, lngEL, lngEC
sProc = oMod.ProcOfLine(lngSL, vbext_pk_Proc)
Debug.Print sActiveProject, sActModule, sProc
Debug.Print Err.Number, Err.Description
End Sub
在另一个模块中,我放置了测试
Sub errTest()
On Error GoTo Err_Control
Dim v As Integer
v = 1E+43
Debug.Print v
Exit_Here:
Exit Sub
Err_Control:
Select Case Err.Number
'Add your Case selections here
Case Else
ActiveCode
Err.Clear
Resume Exit_Here
End Select
End Sub
谢谢。。当我有空闲的几分钟时,我会检查出来。
页:
[1]