|
本帖最后由 tanhong 于 2010-10-31 15:56 编辑
6.11 代码模块中删除代码操作
6.11.1 删除指定行代码
- '过程功能:删除指定行代码
- '输入参数:VBCompName (String字符串变量) 指定模块名
- ' StartLine 代码起始行
- ' LinesNum 代码行数,默认为一行
- Sub DelLinesCodes (VBCompName As String, StartLine As Long, _
- Optional LinesNum As Long = 1)
- Dim VBProj As VBProject
- Dim VBComps As VBComponents
-
- Set VBProj = VBE.ActiveVBProject
- Set VBComps = VBProj.VBComponents
-
- VBComps(VBCompName).CodeModule.DeleteLines StartLine, LinesNum
- End Sub
- '******************************************************************
- '调用示例一:删除"模块1"中,第一行代码
- Call DelLinesCodes("模块1", 1)
- '******************************************************************
- '调用示例二:删除"模块1"中,从第一行到第十行代码
- CAll DelLinesCodes("模块1", 1, 10)
复制代码
6.11.2 删除指定过程所有代码
- '删除指定过程代码
- Public Sub DelProcCodes(VBCompName As String, VBProcName As String)
- Dim VBProj As VBProject
- Dim VBComps As VBComponents
- Dim ProcKind As vbext_ProcKind
-
- Set VBProj = VBE.ActiveVBProject
- Set VBComps = VBProj.VBComponents
-
- With VBComps (VBCompName).CodeModule
- .DeleteLines .ProcStartLine (VBProcName, ProcKind), _
- .ProcCountLines (VBProcName, ProcKind)
- End With
- End Sub
- '******************************************************************
- '调用示例:删除“模块1”中,“我的过程”所有代码
- Call DelProcCodes ("模块1", "我的过程")
复制代码
6.11.3 删除部件或模块中所有代码
- '删除指定模块中所有代码
- Public Sub DelVBCompCodes (ByVal VBCompName As String)
- Dim VBProj As VBProject
- Dim VBComps As VBComponents
-
- '实例对象
- Set VBProj = VBE.ActiveVBProject
- Set VBComps = VBProj.VBComponents
- '从代码模块中第一行到最后一行执行删除
- VBComps(VBCompName).CodeModule.DeleteLines 1, _
- VBComps(VBCompName).CodeModule.CountOfLines
- End Sub
- '******************************************************************
- '调用示例:删除“模块1”中所有代码
- Call DelVBCompCodes ("模块1")
复制代码
6.12 添加事件过程代码操作
6.12.1 向指定部件对象添加事件
- '过程功能:创建一个事件过程
- '输入参数:VBCompNameOrIndex(Variant)部件名或索引
- ' strEventProc(String)事件程序
- ' strEventObj(String)事件对象
- ' strInsertCode(String)事件中欲插入代码,默认为空
- Sub CreateEventProcCode (VBCompNameOrIndex As Variant, _
- strEventProc As String, _
- strEventObj As String, _
- Optional strInsertCode As String = "")
- Dim VBProj As VBProject
- Dim VBComp As VBComponent
- Dim CodeMod As CodeModule
- Dim LineNum As Long
-
- '实例化对象
- Set VBProj = VBE.ActiveVBProject
- Set VBComp = VBProj.VBComponents (VBCompNameOrIndex)
- Set CodeMod = VBComp.CodeModule
-
- With CodeMod
- LineNum = .CreateEventProc (strEventProc, strEventObj)
-
- '是否为事件添了代码,如未添加则退出
- If strInsertCode = vbNullString Then Exit Sub
- '从事件代码之后插入新代码
- LineNum = LineNum + 1
- .InsertLines LineNum, strInsertCode
- End With
- End Sub
- '************************************************
- '调用示例一:在窗体1中创建窗体加载事件,并加入代码
- Dim strProcCode As String
- strProcCode = Space(4) & "Msgbox " & Chr(34) & "这是创建事件代码演示!"
- Call CreateEventProcCode("Form_窗体1", "Load", "Form", strProcCode)
- '************************************************
- '调用示例二:在窗体1中创建窗体打开事件,但不加入代码
- Call CreateEventProcCode("Form_窗体1", "Open", "Form")
复制代码 |
|