Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/vba/15.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
PowerShell在Excel VBA中插入代码_Vba_Excel_Powershell - Fatal编程技术网

PowerShell在Excel VBA中插入代码

PowerShell在Excel VBA中插入代码,vba,excel,powershell,Vba,Excel,Powershell,我正在为我的工作创建一个脚本,我需要在Excel中插入一些VBA代码。除了如何在VBProject中插入代码外,我已经解决了所有问题。我需要插入2个代码。我需要在Sheet1(又名tmpArk1)和本工作簿中插入一个代码。我该怎么做 到目前为止,我的代码是: Function Get-FileName($initialDirectory) { [System.Reflection.Assembly]::LoadWithPartialName("System.windows.forms") |

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

到目前为止,我的代码是:

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
不能对空值表达式调用方法。
在C:\Users\G017116\Desktop\PowerShell InWork.ps1:995 char:57

+$ExcelModuleAlfa=$workbook2.VBProject.VBComponents.Add尝试以管理员身份运行PowerShell

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

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

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

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

$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文档去验证权限)

可能重复的代码我已经看过他的代码,ofc也试过了。但我似乎无法让它工作。不太确定我做错了什么,但它找不到VBA表