如何在powershell中的excel.Worksheet中添加VBA代码?

Alb*_*ban 4 excel powershell vba excel-vba

我需要Private Sub **Worksheet_BeforeDoubleClick** (ByVal Target As Range, Cancel As Boolean)在我的表格中包含一个(1).

我能够正确地打开和写入单元格,但我不知道如何将VBA代码放在工作表中(而不是在VBA模块中).

$excel = New-Object -ComObject Excel.Application
$workbook = $excel.Workbooks.Add()
$worksheet = $workbook.WorkSheets.item(1)
$worksheet.range("c1","g6").value = "str"
...
$workbook.SaveAs($xlFlie, 50)
$Excel.Application.Quit()
Run Code Online (Sandbox Code Playgroud)

我试过这个:

$xlmodule = $workbook.VBProject.VBComponents.Add()
$xlmodule.CodeModule.AddFromString($code)
Run Code Online (Sandbox Code Playgroud)

但我得到了这个错误:

Can not call a method in an expression Null.
Au caractère .\Build-ADGrpsMembers2Excel.ps1:273 : 5
+     $xlmodule = $workbook.VBProject.VBComponents.Add(1)
+     ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo          : InvalidOperation : (:) [], RuntimeException
+ FullyQualifiedErrorId : InvokeMethodOnNull
Run Code Online (Sandbox Code Playgroud)

Alb*_*ban 7

我需要将VBA选项更改为

$excel = New-Object -ComObject Excel.Application
New-ItemProperty -Path "HKCU:\Software\Microsoft\Office\$($excel.Version)\excel\Security" -Name AccessVBOM -Value 1 -Force | Out-Null
New-ItemProperty -Path "HKCU:\Software\Microsoft\Office\$($excel.Version)\excel\Security" -Name VBAWarnings -Value 1 -Force | Out-Null
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述

我的工作代码是:

$excel = New-Object -ComObject Excel.Application
New-ItemProperty -Path "HKCU:\Software\Microsoft\Office\$($excel.Version)\excel\Security" -Name AccessVBOM -Value 1 -Force | Out-Null
New-ItemProperty -Path "HKCU:\Software\Microsoft\Office\$($excel.Version)\excel\Security" -Name VBAWarnings -Value 1 -Force | Out-Null

$workbook = $excel.Workbooks.Add(1)
$worksheet=$workbook.WorkSheets.item(1)

$excel.Visible=$true
$excel.DisplayAlerts = $true
$excel.ScreenUpdating = $true

#$worksheet.range("c1","f6").ColumnWidth = 4
#$worksheet.range("c1","f6").Orientation = 90

$xlmodule = $workbook.VBProject.VBComponents.item('feuil1')
$code = @"
Private Sub Worksheet_BeforeDoubleClick(ByVal Target As Range, Cancel As Boolean)
End Sub
"@

$xlmodule.CodeModule.AddFromString($code)

$saveName = "$([Environment]::GetFolderPath('desktop'))\Export-Excel ($( ((Get-Date -Format u ) -replace ":", ".") -replace "Z", '' ) ).xlsb"

# savegarde du fichier
$workbook.SaveAs($saveName, 50)

Write-Verbose "Closing $($WorkSheetName)"
$Excel.Workbooks.Close()
Write-Verbose "Exit Excel"
$Excel.Application.Quit
Run Code Online (Sandbox Code Playgroud)