Private Sub CommandButton1_Click()
Dim Wbk As Workbook
Set Wbk = Workbooks.Add
Dim w1 As String
'构造代码
w1 = "Private Sub Workbook_Open()"
w1 = w1 & vbCrLf & "MsgBox ""我是被克隆出来的,呵呵!"""
w1 = w1 & vbCrLf & "End Sub"
Dim VBC
For Each VBC In Wbk.VBProject.VBComponents
If VBC.Name = Wbk.CodeName Then
'删除所有代码
VBC.CodeModule.DeleteLines 1, VBC.CodeModule.CountOfLines
'插入新代码
VBC.CodeModule.InsertLines 1, w1
Exit For '跳出循环
End If
Next
'保存工作簿
'Wbk.SaveAs "c:\obs\obs1.xls"
Set Wbk = Nothing
End Sub
这是网上一段代码
转不成功 求指点
#include <Excel.au3>
Local $oExcel = _ExcelBookNew()
;~ ' Place code in a string.
$strCode = _
'Private Sub Worksheet_BeforeDoubleClick(ByVal Target As Range, Cancel As Boolean)' & @CRLF & _
'If Target.Interior.ColorIndex = 22 Then' & @CRLF & _
'Target.Interior.ColorIndex = 0' & @CRLF & _
'Else' & @CRLF & _
'Target.Interior.ColorIndex = 22' & @CRLF & _
'End If' & @CRLF & _
'End Sub'
Dim $VBC
For $VBC In $oExcel.VBProject.VBComponents
If $VBC.Name = $oExcel.CodeName Then
$VBC.CodeModule.DeleteLines( 1, $VBC.CodeModule.CountOfLines)
;'插入新代码
$VBC.CodeModule.InsertLines(1, $strCode)
ExitLoop; '跳出循环
EndIf
Next
|