如何用VB给已存在的EXCEL文件加上宏代码,而且必须加在Workbook_BeforeClose和workbook_BeforeSave事件里?
如何用VB给已存在的EXCEL文件加上宏代码,而且必须加在Workbook_BeforeClose和workbook_BeforeSave事件里?\
我在做一个程序,目标是将用户做好的EXCEL文件用VB编写的这个软件,自动加上宏代码。并且要加在上面所讲的两个事件里,而且前面还要有几行声明。
最好给出示范代码。如果直接写自定义函数型的宏代码就算了。我不需要。只需要在上述两个事件中如何加入代码?
还有如何用VB自动给代码加上密码保护?
在线等。解决马上给分。
[解决办法]
'引用Microsoft Visual Basic for Applications Extensibility
'引用Microsoft Ecxel 11.0 object library
Private Sub Command1_Click()
Dim xlApp As Excel.Application
Dim xlBook As Excel.Workbook
Set xlApp = New Excel.Application
Set xlBook = xlApp.Workbooks.Open("D:\Mytest\20100209\test.xls")
xlApp.Visible = True
xlBook.VBProject.VBComponents(xlBook.CodeName).CodeModule.InsertLines 1, "Private Sub Workbook_BeforeClose(Cancel As Boolean)"
xlBook.VBProject.VBComponents(xlBook.CodeName).CodeModule.InsertLines 2, "End Sub"
End Sub
[解决办法]
楼主试一下这个代码:
Option ExplicitPrivate Sub InstCodes() Dim objExcelApp As Object, objWorkBook As Object Dim strCodeText As String strCodeText = "Private Sub Workbook_BeforeClose(Cancel As Boolean)" & vbCrLf _ & " '这是""Workbook_BeforeClose()""事件代码" & vbCrLf _ & "End Sub" & vbCrLf & vbCrLf _ & "Private Sub Workbook_BeforeSave(ByVal SaveAsUI As Boolean, Cancel As Boolean)" & vbCrLf _ & " '这是""Workbook_BeforeSave()""事件代码" & vbCrLf _ & "End Sub" Set objExcelApp = CreateObject("Excel.Application") Set objWorkBook = objExcelApp.Workbooks.Open("X:\Temp\Book1.xls") Dim i&: i = objWorkBook.VBProject.VBComponents("ThisWorkbook").CodeModule.CountOfLines + 1 objWorkBook.VBProject.VBComponents("ThisWorkbook").CodeModule.InsertLines i, strCodeText objExcelApp.DisplayAlerts = False objWorkBook.Close True: DoEvents Set objWorkBook = Nothing objExcelApp.quit Set objExcelApp = NothingEnd SubPrivate Sub Command1_Click() Call InstCodesEnd Sub