I want to write a Powershell Script, which opens a existing file and puts a macro in it. Im searching and searching, but I found nothing.
My Code is:
$Word = New-Object -ComObject Word.Application
$Word.Visible = $true
$filepathagenda = "C:\Users\$Username\Desktop\Agenda.docx"
$Word.Documents.Open($filepathagenda)
The VBA code is:
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
How can i put a Macro into the file ? I just found some commands, where i can run a macro, but nothing about embedding a macro into a file like that. After the Script is embed into the docx/docm File i want to run the macro in the file with:
$word.run("Macroname")
$word.quit() exit application