Powershell脚本包括。 VBA Excel宏

问题描述 投票:2回答:1

我想编写一个Powershell脚本,它打开一个现有文件并在其中放入一个宏。我正在搜索和搜索,但我一无所获。

我的代码是:

$Word = New-Object -ComObject Word.Application
$Word.Visible = $true
$filepathagenda = "C:\Users\$Username\Desktop\Agenda.docx"
$Word.Documents.Open($filepathagenda)

VBA代码是:

Sub Macroname()
    Dim oTab As Table
    Dim i As Integer
    Dim x As Integer
    Dim Std As Double
    Dim Min As Double
    Dim Dauer As Double
    Dim Z As Double
    Dim ZInt As Double
    Dim ZDez As Double
    Dim Txt As String

    Set oTab = ActiveDocument.Tables(1)
    i = oTab.Rows.Count

    For x = 2 To i    
        On Error GoTo ErrorHandle:

        Std = CDbl(Left(oTab.Cell(x, 5), 2))
        Min = CDbl(Mid(oTab.Cell(x, 5), 4, 2))
        Txt = oTab.Cell(x, 4).Range.Text

        Dauer = CDbl(Left(oTab.Cell(x, 4), Len(Txt) - 2))

        If Min + Dauer < 60 Then
            oTab.Cell(x + 1, 5).Range.Text = Format(Std, "00") & ":" & Format(Min + Dauer, "00")
            oTab.Cell(x + 1, 5).Select
        Else
            Z = (Min + Dauer) / 60
            ZDez = Z - Int(Z)
            ZDez = ZDez * 60
            oTab.Cell(x + 1, 5).Range.Text = Format(Std + Int(Z), "00") & ":" & Format(ZDez, "00")
            oTab.Cell(x + 1, 5).Select
        End If

        GoTo NoError:

ErrorHandle:
    oTab.Cell(x + 1, 5).Range.Text = Format(Std, "00") & ":" & Format(Min, "00")
    oTab.Cell(x + 1, 5).Select
    Resume NoError:

NoError:
    Next x

Ende:
End Sub

如何将宏放入文件中?我刚刚发现了一些命令,我​​可以运行一个宏,但没有关于将宏嵌入到这样的文件中。将脚本嵌入docx / docm文件后,我想在文件中运行宏:

$word.run("Macroname") 
$word.quit() exit application
excel vba powershell
1个回答
3
投票

您可能正在寻找Word文档的.Import method

objDocumentObject.VBProject.VBComponents.Import(strFilePathAndName)

其中strFilePathAndName是对包含宏的文本文档的引用。

下面使用FileDialog方法选择Word文档并逐行插入宏作为字符串,但也可以通过使用上述方法引用文件名变量来完成。

Sub AddMacroToWordDoc()
    With Application.FileDialog(msoFileDialogOpen)
        .Show
        Dim appWord As Word.Application
        Set appWord = New Word.Application

        Dim docDocToAdjust As Word.Document
        Set docDocToAdjust = appWord.Documents.Open(Trim(.SelectedItems(1)))

        docDocToAdjust.VBProject.VBComponents("ThisDocument") _
            .CodeModule.AddFromString _
            "Sub Test()" & vbLf & _
            "  MsgBox ""It works""" & vbLf & _
            "End Sub"
    End With
End Sub

值得注意的是,这两种方法都要求在VBA代码插入工作之前信任文件(原因很明显)。

编辑:如果您在其他Microsoft产品的VBA中使用此功能,则还需要引用Microsoft Word对象库。

© www.soinside.com 2019 - 2024. All rights reserved.