How to add VBA code to Excel worksheet using PowerShell?

后端 未结 2 1064
伪装坚强ぢ
伪装坚强ぢ 2021-01-05 12:56

I need to include a Private Sub Worksheet_BeforeDoubleClick (ByVal Target As Range, Cancel As Boolean) in my Sheet(1).

I\'m able to open and write in ce

2条回答
  •  不思量自难忘°
    2021-01-05 13:10

    This answer helped me a lot but I had to add another module, so I did something like this

    $workbook.VBProject.VBComponents.Add(1) 
    $workbook.VBProject.VBComponents.Add(2) 
    $workbook.VBProject.VBComponents.Add(3) 
    

    1 is for module, 2 is for userform, 3 is for class

    to grab just-added module it will be in the last place in the array of Components

    $arrayOfComponents = @($workbook.VBProject.VBComponents)
    $justAddedModule = $arrayOfComponents[$arrayOfComponents.Length-1]
    

    so it looks something like this

    $excel = New-Object -ComObject Excel.Application
    $vbaProject = new-object -ComObject VB
    $FilePath = "c:\temp\excel.xlsm"
    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($FilePath)
    # Add(1) za dodavanje modula
    #$workbook.VBProject.VBComponents.Add(1)
    
    $xlmodule = $workbook.VBProject.VBComponents.item('Module1')
    
    
    $code = @"
    Sub test()
    '
    End Sub
    "@
    $xlmodule.CodeModule.AddFromString($code)
    $workbook.SaveAs($FilePath,52)
    $excel.Workbooks.Close() 
    $excel.Application.Quit()
    

提交回复
热议问题