用VB怎样向EXCEL中的宏传递数据?

解决方案 »

  1.   

    引用EXCEL
    引用Microsoft Visual Basic for Applications Extensibility
    Private Sub Command1_Click()
    Dim xl As Excel.Application
    Dim bk As Workbook
    Dim xlcomp As VBComponent
    Set xl = New Excel.Application
    Set bk = xl.Workbooks.Add
    On Error Resume Next
    Set xlcomp = xl.VBE.VBProjects(1).VBComponents.Add(vbext_ct_StdModule)
    If Err.Number <> 0 Then MsgBox Err.Description & Chr(10) & "请设置EXCEL中的宏安全性---可靠来源": Exit Sub
    xlcomp.CodeModule.AddFromString "sub gg()" & Chr(10) _
                      & "msgbox " & """" & "OK" & """" & Chr(10) _
                      & "end sub"
    xl.Visible = True
    xl.Run "gg"
    End Sub
    以上是exel,下面是word哈哈,这个问题我自己解决了,我这个打开别人的文件并且加入了宏,实现痕迹保留,注意这个技术不许用来开发宏病毒!!
    Private Sub Command1_Click()
    Dim wd As Word.Application
    Dim mydoc As Document
    Dim xlcomp As VBComponent
    Set wd = New Word.ApplicationSet mydoc = wd.Documents.Open("D:\Documents and Settings\pw-panyg\My Documents\f.doc")
    On Error Resume Next
    Set xlcomp = wd.VBE.VBProjects(1).VBComponents.Add(vbext_ct_StdModule)
    If Err.Number <> 0 Then MsgBox Err.Description & Chr(10) & "请设置word中的宏安全性---可靠来源": Exit Sub
    xlcomp.CodeModule.AddFromString "sub MySub()" & Chr(10) _
                      & "With ActiveDocument" & Chr(10) _
                      & ".TrackRevisions = True" & Chr(10) _
                      & ".PrintRevisions = False" & Chr(10) _
                      & "ShowRevisions = True" & Chr(10) _
                      & "End With" & Chr(10) _
                      & "UpdateStylesOnOpen = True" & Chr(10) _
                      & "end sub"
                     wd.Visible = True
    wd.Run "MySub"
    '关闭和存储还有判断是否从新加入删除别人的宏没做,以后再细做!!
    我好牛鼻啊,哈哈,有成就感!!~~~
    End Sub