2017-05-28 63 views
-1

我有以下代碼,其中對於列A,我試圖對任何等於102的值執行紅色突出顯示,對於等於101的任何值,併爲任何值等於100的藍色突出顯示。如何使用Powershell在Excel列中突出顯示某些值

我認爲問題出現在我的上一節(### Super If語句##)中,因此只想查看參數的正確代碼是什麼上面的段落? 由於

#Open Up the Workbook# 
$excel = new-object -comobject Excel.Application 
$excel.visible = $false 
$workbook = $excel.workbooks.open("c:\scripts\test.xlsx") 
$worksheet = $workbook.Worksheets.Item(1) 
$rows = $worksheet.range("A1").currentregion.rows.count 

#A Formula# 
$worksheet.range("A2:A$rows").formula = "=B2+100" 
[void]$worksheet.Cells.Item(1,1).select() 
$excel.visible = $true 

#Today + 1 Formula# 
$worksheet.range("C2:C$rows").formula = "=TODAY()+1" 
[void]$worksheet.Cells.Item(1,1).select() 
$excel.visible = $true 

#INJECTED WITH A POISON# 
$worksheet.range("C1").formula = "The Official Formula" 
[void]$worksheet.Cells.Item(1,1).select() 
$excel.visible = $true 

#Set up a filter 
$headerRange = $worksheet.Range("a1","c1") 
$headerRange.AutoFilter() | Out-Null 
$Excel.Rows.Item(1).Font.Bold = $true 

#Super If Statement## 
IF ($worksheet.range("A2:A$rows") -eq "102") { 
    $worksheet.range.Interior.ColorIndex =3} 
ElseIF ($worksheet.range("A2:A$rows") -eq "101") { 
    $worksheet.range.Interior.ColorIndex =6} 
ElseIF ($worksheet.range("A2:A$rows") -eq "100") { 
    $worksheet.range.Interior.ColorIndex =5} 
+0

在## Super If Statement ##部分中,我添加了關閉')',但沒有收到任何錯誤消息。但是,當Excel表彈出時,即使其明確指出(例如102應該是紅色陰影),值也不會突出顯示 – jreyez

+0

是否在102和「102」之間混合?我在本地運行你的代碼,似乎沒問題。 但我確實使用foreach遍歷頭文件而不是If/else開關。 – SAm

+0

我不這麼認爲。我已經替換了沒有引用的值,並彈出相同的情況。儘管沒有錯誤信息。你使用foreach的代碼是什麼?這可能有用@SAm – jreyez

回答

1

使用@SAm示例代碼,我在##Super Foreach Statement##與代碼替換#Super If Statement##如下所示。以下代碼現在能夠按預期執行。

#Open Up the Workbook# 
$excel = new-object -comobject Excel.Application 
$excel.visible = $false 
$workbook = $excel.workbooks.open("c:\scripts\test.xlsx") 
$worksheet = $workbook.Worksheets.Item(1) 
$rows = $worksheet.range("A1").currentregion.rows.count 

#A Formula# 
$worksheet.range("A2:A$rows").formula = "=B2+100" 
[void]$worksheet.Cells.Item(1,1).select() 
$excel.visible = $true 

#Today + 1 Formula# 
$worksheet.range("C2:C$rows").formula = "=TODAY()+1" 
[void]$worksheet.Cells.Item(1,1).select() 
$excel.visible = $true 

#INJECTED WITH A POISON# 
$worksheet.range("C1").formula = "The Official Formula" 
[void]$worksheet.Cells.Item(1,1).select() 
$excel.visible = $true 

#Set up a filter 
$headerRange = $worksheet.Range("a1","c1") 
$headerRange.AutoFilter() | Out-Null 
$Excel.Rows.Item(1).Font.Bold = $true 

#Super ForEach Statement ## 
$worksheet.Range('A2:A100')|%{ if($_.text -match '102'){ $_.interior.colorindex = 3 } } 
$worksheet.Range('A2:A100')|%{ if($_.text -match '101'){ $_.interior.colorindex = 6 } } 
$worksheet.Range('A2:A100')|%{ if($_.text -match '100'){ $_.interior.colorindex = 5 } } 
相關問題