Saving VBA Script to Microsoft Excel Objects > thisworbook.cls

Mark Verhunce 41 Reputation points
2022-05-26T19:43:39.697+00:00

I am using PowerShell to create open a .xlsx, then save it as a macro enabled workbook (.xlsm) and it adds a vb script to vba projects > modules with
$AutofitModule = $workbook.VBProject.VBComponents.Add(1)
$Autofit = @"
Sub workbook_open()
Worksheets("Sheet1").UsedRange.EntireColumn.autofit
End Sub
"@

$AutoFitModule.codemodule.AddFromString($Autofit)

Instead of saving this to vba projects > modules as the first image shows, I would like to save it to vbaprojects > Microsoft Excel Opbjects > Thisworkbook as the 2nd image shows.

Any help is greatly appreciated205906-vba-module.png205981-vba-workbook.png

Windows for business | Windows Server | User experience | PowerShell
Developer technologies | Visual Basic for Applications
0 comments No comments
{count} votes

1 answer

Sort by: Most helpful
  1. kinuasa 371 Reputation points
    2022-05-30T04:06:30.99+00:00

    Specify ThisWorkbook in the VBComponent object.

    $workbook.VBProject.VBComponents("ThisWorkbook").CodeModule.AddFromString($Autofit)
    
    0 comments No comments

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.