powershell - 如何使用 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()
方法无济于事。
引用变量来命名工作表的最佳方法是什么?任何帮助将不胜感激!
解决方案
使用这样的语句将处理它。在变量名两边加上引号。
# change the name of the sheet
$ws.Name = "$NewSheetName"
我不知道为什么,但即使使用明显是字符串的变量,excel 工作表名称也需要引号中的字符串。
笔记
使用 powershell v5 和 Office 2013、Office 365 测试,带有 $variable 的代码没有报价工作正常。不确定究竟是什么导致了您需要double quotes
在变量名周围使用的问题。
推荐阅读
- c++ - 如何使用 cmake 包含 .so 库
- asp.net-core - 使用 Mailkit 的 asp.net 核心 mvc 应用程序中选定下拉值的 NULLReferenceException
- oracle - Oracle join 返回太多行
- java - Java 中的 Rest 服务从 Tomcat 服务器运行,但不在 Eclipse 内部
- node.js - Nodejs api 不接受 POST 方法,错误 405
- javascript - 当我尝试测试我的重试 util 函数时,jest.advanceTimersByTime 不起作用
- java - 我想在 Flux 中动态添加对象
- email - Sendgrid 电子邮件模板深色模式
- c - 如何跳过 n 的第二个输入
- json - 从计数器附加 JSON