【问题标题】:Conditional formatting - highlighting in VBA条件格式 - 在 VBA 中突出显示
【发布时间】:2020-02-24 04:08:59
【问题描述】:

如果行包含单词“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

这就是我希望它在 VBA 中设置的方式

【问题讨论】:

  • 我相信你可能需要xlExpression而不是xlGreater
  • @cybernetic.nomad 这就是答案。做出官方回答,这样就可以关闭了。 docs.microsoft.com/en-us/office/vba/api/…
  • 您好,谢谢您的建议,但我在“Set rng = ("A1, AZ2000") 也收到一条错误消息,它说类型不匹配,是因为我设置了错误的范围吗?
  • 可能是"Set rng = ("A1:AZ2000")"?

标签: excel conditional-statements highlight


【解决方案1】:

这应该可行。

我不知道您将此应用于哪个工作簿,所以我给了您一些选项,删除 set wbsheetID 之前的 ',具体取决于您要使用的工作簿(并将其添加到其他工作簿中) )。如果您对使用 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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-05-02
    • 2016-09-07
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多