在Excel中根据文本值设置单元格颜色 – VBA

我正在编写一个脚本来在机器上运行ping 。 该脚本使用主机名查找文本文件,并返回列A中的主机名和列B中的ping (上或下)状态。

我需要列B颜色更改为绿色,如果向上和红色,如果向下。

代码没有问题:

 '# call excel applicationin visible mode Set objExcel = CreateObject("Excel.Application") objExcel.Visible = True objExcel.Workbooks.Add intRow = 2 '# Define Labels objExcel.Cells(1, 1).Value = "Machine Name" objExcel.Cells(1, 2).Value = "Results" '# Create file system object for reading the hosts from text file Set Fso = CreateObject("Scripting.FileSystemObject") Set InputFile = fso.OpenTextFile("MachineList.Txt") '# Loop thru the text file till the end Do While Not (InputFile.atEndOfStream) HostName = InputFile.ReadLine '# Create shell object for Pinging the host machines Set WshShell = WScript.CreateObject("WScript.Shell") Ping = WshShell.Run("ping -n 1 " & HostName, 0, True) objExcel.Cells(intRow, 1).Value = HostName '# use switch case for checking the machine updown status Select Case Ping Case 0 objExcel.Cells(intRow, 2).Value = "up" Case 1 objExcel.Cells(intRow, 2).Value = "down" End Select intRow = intRow + 1 Loop '# Format the excel objExcel.Range("A1:B1").Select objExcel.Selection.Interior.ColorIndex = 19 objExcel.Selection.Font.ColorIndex = 11 objExcel.Selection.Font.Bold = True objExcel.Cells.EntireColumn.AutoFit 

我曾尝试过的颜色(很多问题):

 Sub ColorCells() Dim cel As Range Application.ScreenUpdating = False Application.EnableEvents = False For Each cel In Range("B2:B90") Select Case LCase(Left(cel.Value, 1)) Case "up" cel.Interior.Color = vbGreen Case Else cel.Interior.ColorIndex = xlColorIndexNone End Select Next cel Application.EnableEvents = True Application.ScreenUpdating = True End Sub 

我得到:

我得到了什么

我想要的是:

我想要的是

当您插入“向上”或“向下”时,要更改单元格的颜色,请将Select Case Pingreplace为以下内容:

 Select Case Ping Case 0 objExcel.Cells(intRow, 2).Value = "up" objExcel.Cells(intRow, 2).Interior.Color = vbGreen Case 1 objExcel.Cells(intRow, 2).Value = "down" objExcel.Cells(intRow, 2).Interior.Color = vbRed End Select 
 Select Case Ping Case 0 objExcel.Cells(intRow, 2).Value = "up" objExcel.Cells(intRow, 2).Interior.Color = vbGreen Case 1 objExcel.Cells(intRow, 2).Value = "down" objExcel.Cells(intRow, 2).Interior.Color = vbRed End Select 

这将是如何实现selectCase语句中的颜色。 下面看看我的使用虽然因为它是一个比使用更好的方法。select(而不是在问题中的最后一行代码):

 With objExcel.Range("A1:B1") .Interior.ColorIndex = 19 .Font.ColorIndex = 11 .Font.Bold = True End With objExcel.Cells.EntireColumn.AutoFit