如何使用PowerShell插入Excel公式?

时间:2017-05-17 14:58:59

标签: excel string powershell excel-formula automation

公式=LEFT(AB4,FIND(" ",AB5)-1在Excel中完美运行,但似乎在PowerShell中导致错误,我收到此错误:

Exception from HRESULT: 0x800A03EC
At C:\Scripts\Excel_NUID2.ps1:21 char:1
+ $worksheet.range("AH5:AH$rows").formula = "=LEFT(AB4,FIND(" ",AB5)-1"
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo          : OperationStopped: (:) [], COMException
+ FullyQualifiedErrorId : System.Runtime.InteropServices.COMException 

我的PowerShell脚本代码;

#Open Up the Workbook#
$excel = new-object -comobject Excel.Application
$excel.visible = $false  
$workbook = 
$excel.workbooks.open("c:\Users\Jack\documents\NUID_Status_Report.xlsx") 
$worksheet = $workbook.Worksheets.Item(1)

$rows = $worksheet.range("A1").currentregion.rows.count

### Set up a filter ###
$headerRange = $worksheet.Range("a4","aj4")
$headerRange.AutoFilter() | Out-Null

#### Trims Password Expiration Date Name ###

$worksheet.range("AH4").formula = "Shortened Expiration Date"
[void]$worksheet.Cells.Item(1,1).select()
$excel.visible = $true

#### Trims Password Expiration Date Formula ###

$worksheet.range("AH5:AH$rows").formula = "=LEFT(AB4,FIND(" ",AB5)-1"
[void]$worksheet.Cells.Item(1,1).select()
$excel.visible = $true

1 个答案:

答案 0 :(得分:1)

引用字符串中的引号需要加倍。

$worksheet.range("AH5:AH$rows").formula = "=LEFT(AB4,FIND("" "",AB5)-1)"
'you can also get rid of the inside quotes with the CHAR function
$worksheet.range("AH5:AH$rows").formula = "=LEFT(AB4, FIND(CHAR(32), AB5)-1)"

ASCII字符32是一个空格。我还添加了一个括号来制定合法的公式。