gpt4 book ai didi

excel - 如何使用 PowerShell 将 VBA 代码添加到 Excel 工作表?

转载 作者:行者123 更新时间:2023-12-02 10:00:40 26 4
gpt4 key购买 nike

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

我能够打开单元格并在单元格中写入。

$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()

如何将 VBA 代码放入工作表中(而不是放入 VBA 模块中)?

我尝试过这个:

$xlmodule = $workbook.VBProject.VBComponents.Add()
$xlmodule.CodeModule.AddFromString($code)

我收到此错误:

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

最佳答案

我需要将 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

enter image description here

我的工作代码是:

$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

关于excel - 如何使用 PowerShell 将 VBA 代码添加到 Excel 工作表?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21278760/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com