条件格式-在VBA中突出显示

时间:2019-10-28 21:25:14

标签: excel conditional-statements highlight

如果行中包含单词“ New”,我试图使VBA突出显示整个行。

条件格式的应用范围,我试图将A1放到AZ2000

原因,整个工作表的设置范围也有问题。

我从未学习过VBA,所以我正在从互联网上获取信息

我写了这么多,但据我所知,它没有用,但我不知道为什么它不起作用,令人沮丧,如何解决,我又解决了另一个问题……哈哈

Sub Highlighting()

  'Definining the variables:
  Dim rng As Range
  Dim condition1 As FormatCondition

 'Fixing/Setting the range on which conditional formatting is to be desired
  Set rng = ("A1, AZ2000")

  'To delete/clear any existing conditional formatting from the range
   ws.FormatConditions.delete

  'This is where I get Syntax error, it says "New" needs list separator
  Set condition1 = ws.FormatConditions.Add(xlConditionValueFormula, xlGreater, "=FIND(""New"",$AF1)>0)")

  'Defining and setting the format to be applied for each condition
   With condition1
    .EntireRow.Interior.ColorIndex = 10498160
   End With

End Sub

enter image description here

这就是我想要在VBA中设置的方式

1 个答案:

答案 0 :(得分:0)

这应该有效。

我不知道您将其应用于哪个工作簿,所以我给了您一些选择,根据您要使用的选择,删除'set wb之前的sheetID并将其添加到其他)。如果您对使用vba check out this answer.

进行编码的一些更常见的技巧感兴趣
Sub Highlighting()

'Definining the variables:
Dim rng As String
Dim condition1 As FormatCondition
Dim wb As Workbook
Dim sheetID As String

'Define workbook to run code against, depending on which fits you comment out/in here:
Set wb = ThisWorkbook ' the excel workbook that contains the vba code
'set wb = Workbooks("nameOfExcelWorkbook.xlsx") ' excel workbook that you've defined (must be an open workbook with the name.file ending inside citation marks)
'set wb = ActiveWorkbook ' the currently selected excel workbook (not recommended)
'Set wb = Workbooks.Open("Filename as string.fileEnding")

'Define what sheet to use
sheetID = ActiveSheet.Name 'currently selected worksheet name (not recommended)
'sheetID = "nameOfSheet"
'sheetID = 1 ' indexed version of above

'Fixing/Setting the range on which conditional formatting is to be desired
rng = "A1:AZ2000"


With wb.Sheets(sheetID).Range(rng)

    'To delete/clear any existing conditional formatting from the range
    .FormatConditions.Delete

    'Apply conditional formating
    Set condition1 = .FormatConditions.Add(Type:=xlExpression, Formula1:="=FIND(""New"",$AF1)>0")

End With
'Defining and setting the format to be applied for each condition
With condition1
    .Interior.Color = RGB(112, 48, 160)
End With

End Sub