PowerShell在Excel VBA中插入代码

时间:2016-01-14 09:42:20

标签: vba excel-vba powershell excel

我正在为我的工作创建一个脚本,我需要在Excel中插入一些VBA代码。我已经解决了,除了如何在VBProject中插入代码。我需要插入2个代码。我需要在Sheet1(aka tmpArk1)和ThisWorkbook中插入代码。我该怎么做?

到目前为止我的代码:

Function Get-FileName($initialDirectory)
{
[System.Reflection.Assembly]::LoadWithPartialName("System.windows.forms") |   Out-Null

$OpenFileDialog = New-Object System.Windows.Forms.OpenFileDialog
$OpenFileDialog.initialDirectory = $initialDirectory
$OpenFileDialog.filter = "xlsx (*.xlsx)| *.xlsx"
$OpenFileDialog.ShowDialog() | Out-Null
$OpenFileDialog.filename
}

$inputplace = Get-FileName "P:\" ".xlsx"
$inputname = [System.IO.Path]::GetFileNameWithoutExtension($inputplace)
$inputpath = [System.IO.Path]::GetDirectoryName($inputplace)

########################################
########### Starting Excel #############
########################################


$Excel = New-Object -ComObject Excel.Application
$ExcelVersion = $Excel.Version

New-ItemProperty -Path "HKCU:\Software\Microsoft\Office\$ExcelVersion\Excel\Security" -Name AccessVBOM -Value 1 -Force | Out-Null 
New-ItemProperty -Path "HKCU:\Software\Microsoft\Office\$ExcelVersion\Excel\Security" -Name VBAWarnings  -Value 1 -Force | Out-Null

$Excel.Visible = $true
$Excel.DisplayAlerts = $false

########################################
####### Working with workbook ##########
########################################

#Opens workbook to be transfered from, ReadOnly
$workbook1 = $Excel.Workbooks.Open($inputplace,$null, $true)

#Create workbook to work with
$workbook2 = $Excel.Workbooks.add()


########################################
####### The code to be inserted ########
########################################

#Code Alpha

#$codeAlfa = @"
#    Some code here
#"@

#Code beta

#$codeBeta = @"
#    Some code here
#"@


########################################
####### Working with worksheets ########
########################################

#Add 1 worksheets to workbook
$workbook2.Worksheets.Add()

#Transfer Sheet from opened workbook to new workbook
$SheetToCopy = $workbook1.sheets.item(1)
$TransferTarget = $workbook2.sheets.item(1)
$SheetToCopy.copy($TransferTarget)

#Change name of all 4 worksheets
$workbook2.Worksheets.Item(1).name = "tmpArk1"
$workbook2.Worksheets.Item(2).name = "output"
$workbook2.Worksheets.Item(3).name = "net"
$workbook2.Worksheets.Item(4).name = "data"
$workbook2.Worksheets.Item(5).name = "bilag"

#Close Workbook1
$Workbook1.Close()

#inserting the codes
$ExcelModuleAlfa = $workbook2.VBProject.VBComponents.Add(1)
$ExcelModuleAlfa.CodeModule.AddFromString($codeAlfa)

########################################
######### Clean up enviroment ##########
########################################

#Save workbook to hard drive
Add-Type -AssemblyName Microsoft.Office.Interop.Excel
$workbook2.SaveAs("P:\" + $inputname + "_auto",[Microsoft.Office.Interop.Excel.XlFileFormat]::xlExcel8)

#Close workbook and quit Excel
#$Excel.Workbooks.Close()
#$Excel.Quit()

#Stop Excel process
#Get-Process excel | Stop-Process -Force

#Release com object
[System.Runtime.Interopservices.Marshal]::ReleaseComObject($Excel)

当我尝试运行脚本时,我将此作为输出错误。

You cannot call a method on a null-valued expression.
At C:\Users\G017116\Desktop\PowerShell InWork.ps1:995 char:57
+ $ExcelModuleAlfa = $workbook2.VBProject.VBComponents.Add <<<< (1)
+ CategoryInfo          : InvalidOperation: (Add:String) [], RuntimeException
+ FullyQualifiedErrorId : InvokeMethodOnNull

You cannot call a method on a null-valued expression.
At C:\Users\G017116\Desktop\PowerShell InWork.ps1:996 char:42
+ $ExcelModuleAlfa.CodeModule.AddFromString <<<< ($codeAlfa)
+ CategoryInfo          : InvalidOperation: (AddFromString:String) [], RuntimeException
+ FullyQualifiedErrorId : InvokeMethodOnNull

1 个答案:

答案 0 :(得分:1)

尝试以管理员身份运行PowerShell。

当禁用“信任访问VBA项目对象模型”时,我能够复制该问题。是的,两个New-ItemProperty ... HKCU ...设置应该设置这些选项,但访问注册表可能需要管理员访问才能正确设置。

尝试手动设置/验证信任中心权限是否为:

  • 选择“启用所有宏(不推荐;可能有危险的代码可以运行”
  • 选中“信任对VBA项目对象模型的访问权”

Trust Center Settings

尝试在此处运行最小的命令集:

$Excel = New-Object -ComObject Excel.Application
$ExcelVersion = $Excel.Version
New-ItemProperty -Path "HKCU:\Software\Microsoft\Office\$ExcelVersion\Excel\Security" -Name AccessVBOM -Value 1 -Force | Out-Null
New-ItemProperty -Path "HKCU:\Software\Microsoft\Office\$ExcelVersion\Excel\Security" -Name VBAWarnings  -Value 1 -Force | Out-Null
$Excel.Visible = $true
$workbook2 = $Excel.Workbooks.add()
$workbook2.VBProject.VBComponents

最后一个语句$workbook2.VBProject.VBComponents应该返回类似的内容:

Saved           : True
Name            : ThisWorkbook
Designer        :
CodeModule      : System.__ComObject
Type            : 100
VBE             : System.__ComObject
Collection      : System.__ComObject
HasOpenDesigner : False
Properties      : System.__ComObject
DesignerID      :

Saved           : True
Name            : Sheet1
Designer        :
CodeModule      : System.__ComObject
Type            : 100
VBE             : System.__ComObject
Collection      : System.__ComObject
HasOpenDesigner : False
Properties      : System.__ComObject
DesignerID      :

如果没有,或者出错为null,则不会设置信任中心权限。 (您应该能够使用打开的Excel文档去验证权限)