关于vb代码导入word的问题
怎样用代码将vb代码添加到word宏中,就是用vb代码实现word宏中的导入代码功能
[解决办法]
以下是我以前写得一段程序,是新建一个word文档,然后写入宏,再保存;
如果你的文档已经存在,先在程序中打开,再写入宏,再保存就行了。
'1、启动word把 工具--宏--安全性--安全级 选择 低,' 把 工具--宏--安全性--可靠发行商 勾选 信任对于“Visual Basic项目”的访问'2、关闭word'3、在c盘根目录下做一个叫 说明.htm 的文件'4、本程序要先引用Microsoft Word 11.0 Object Library'5、运行本程序,然后再用word打开c:\doc1.doc看看。'6、windows操作系统如不在c:\windows下,请自己修改c:\windows\NOTEPAD.EXE路径和' c:\windows\explorer.exe c:\说明.htm路径'7、寻找windows操作系统路径,可以用API来完成,这是另外一个话题了。Private Sub Command1_Click() Dim app As New Word.Application Dim doc As Word.Document Dim s1 As String, s2 As String app.Visible = False s1 = "Private Sub Document_Open()" & vbCr & _ " Dim iMenu As CommandBarPopup, MyMenu3 As CommandBarButton" & vbCr & _ " Dim MyMenu1 As CommandBarButton, MyMenu2 As CommandBarButton" & vbCr & _ vbCr & _ " For Each iMenu In Application.CommandBars.ActiveMenuBar.Controls" & vbCr & _ " If iMenu.Caption = ""[我的软件名称](&I)"" Then" & vbCr & _ " Exit Sub" & vbCr & _ " End If" & vbCr & _ " Next" & vbCr & _ vbCr & _ " Set iMenu = Application.CommandBars(""Menu Bar"").Controls.Add(Type:=msoControlPopup)" & vbCr & _ " iMenu.Caption = ""[我的软件名称](&I)""" & vbCr & _ vbCr & _ " Set MyMenu1 = iMenu.CommandBar.Controls.Add(Type:=msoControlButton)" & vbCr & _ " MyMenu1.Caption = ""……运行软件""" & vbCr & _ " MyMenu1.OnAction = ""a""" & vbCr & _ vbCr & _ " Set MyMenu2 = iMenu.CommandBar.Controls.Add(Type:=msoControlButton)" & vbCr & _ " MyMenu2.Caption = ""……操作帮助""" & vbCr & _ " MyMenu2.OnAction = ""b""" & vbCr & _ vbCr & _ " Set MyMenu3 = iMenu.CommandBar.Controls.Add(Type:=msoControlButton)" & vbCr & _ " MyMenu3.Caption = ""……删除按钮""" & vbCr & _ " MyMenu3.OnAction = ""c""" & vbCr & _ "End Sub" s2 = "Private Sub a()" & vbCr & _ " '打开记事本,修改成你的程序路径" & vbCr & _ " Shell ""c:\windows\NOTEPAD.EXE"", vbNormalFocus" & vbCr & _ "End Sub" & vbCr & _ vbCr & _ "Private Sub b()" & vbCr & _ " '打开说明文件,修改成你的说明文件路径" & vbCr & _ " Shell ""c:\windows\explorer.exe c:\说明.htm"", vbNormalFocus" & vbCr & _ "End Sub" & vbCr & _ vbCr & _ "Private Sub c()" & vbCr & _ " '删除自定义按钮的方式" & vbCr & _ " Dim iMenu As CommandBarPopup" & vbCr & _ " For Each iMenu In Application.CommandBars.ActiveMenuBar.Controls" & vbCr & _ " If iMenu.Caption = ""[我的软件名称](&I)"" Then" & vbCr & _ " iMenu.Delete" & vbCr & _ " End If" & vbCr & _ " Next" & vbCr & _ "End Sub" s1 = s1 & vbCr & s2 Set doc = Documents.Add '如果这里出现错误,请稍等一会再重新运行程序,可能是word临时文件的事 doc.VBProject.VBComponents("ThisDocument").CodeModule.AddFromString s1 doc.SaveAs FileName:="c:\doc1.doc" doc.Close: Set doc = Nothing app.Quit: Set app = NothingEnd Sub