我正在尝试使用变量使用 Powershell 设置 excel 工作表名称,但收到此错误:
Exception from HRESULT: 0x800A03EC
At line:14 char:1
+ $ws.Name = $RequestTitle
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : OperationStopped: (:) [], COMException
+ FullyQualifiedErrorId : System.Runtime.InteropServices.COMException
下面是一段代码:
# create new excel object
$excel = New-Object -ComObject excel.application
# show the excel object
$excel.visible = $True
# add a workbook
$workbook = $excel.Workbooks.Add()
# create a variable referencing the first sheet of the wb
$ws= $workbook.Worksheets.Item(1)
# change the name of the sheet
$ws.Name = $NewSheetName
但是当我做这样的事情时:$ws.Name = "some string"
它工作正常,没有错误。我也尝试使用$NewSheetName.ToString()
方法无济于事。
引用变量来命名工作表的最佳方法是什么?任何帮助将不胜感激!
像这样使用语句就可以处理它了。在变量名称两边加上引号。
# change the name of the sheet
$ws.Name = "$NewSheetName"
我不知道为什么,但 excel 工作表名称需要引号中的字符串,即使使用明显是字符串的变量也是如此。
注意
使用Powershell v5和Office 2013进行测试,Office 365,带有$variable的代码没有引号工作正常。不确定究竟是什么导致了需要在变量名称周围使用double quotes
的问题。