2017-05-17 87 views
2

=LEFT(AB4,FIND(" ",AB5)-1在Excel中的作品完美,但似乎導致在PowerShell中的錯誤,我得到這個錯誤的公式:如何使用PowerShell插入Excel公式?

 
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 
+0

You state'*公式= LEFT(AB4,FIND(「」,AB5)-1在Excel *中完美工作,但這是不正確的;它在某處丟失了一個右括號 – Jeeped

+0

正確,我一定錯過了右邊應該是= LEFT(AB4,FIND(「」,AB5)-1) – jreyez

回答

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是空格。我還添加了一個支架來制定一個合法的公式。

+0

謝謝Jeeped,它看起來像你的解決方案工作! – jreyez