首页 > 解决方案 > 如何使用 powershell 变量设置 Excel 工作表名称?

问题描述

我正在尝试使用变量使用 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()方法无济于事。

引用变量来命名工作表的最佳方法是什么?任何帮助将不胜感激!

标签: powershell

解决方案


使用这样的语句将处理它。在变量名两边加上引号。

# change the name of the sheet 
$ws.Name = "$NewSheetName"

我不知道为什么,但即使使用明显是字符串的变量,excel 工作表名称也需要引号中的字符串。

笔记

使用 powershell v5 和 Office 2013、Office 365 测试,带有 $variable 的代码没有报价工作正常。不确定究竟是什么导致了您需要double quotes在变量名周围使用的问题。


推荐阅读