![](/img/trans.png)
[英]Simple SaveAs Excel Macro query - Need script updating to incl. filename and .xls extension
[英]Powershell Script incl. VBA Excel Macro
我想編寫一個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
您可能正在尋找Word文檔的.Import
方法 。
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對象庫。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.