【问题标题】:Excel VBA Select Cell RangesExcel VBA 选择单元格区域
【发布时间】:2016-03-05 05:15:49
【问题描述】:

我有以下代码,但在Set CellRange = wks.Range(srange).Select 行出现“需要对象”错误。

我尝试了很多事情,但无法弄清楚。我想根据特定的单元格值在选定范围内设置背景颜色。

Function RowColor()
    Application.Volatile
    Dim wks As Worksheet
    Set wks = ActiveSheet
    Dim x As Integer
    Dim FirstRow As Integer
    Dim CellRange As Range
    Dim LastRow As Long

    LastRow = wks.Cells(wks.Rows.Count, "A").End(xlUp).Row
    FirstRow = 6

    'Loop through each row
    ScreenUpdating = False

    For x = FirstRow To LastRow
     Let srange = "A" & x & ":" & "Z" & x
    Set CellRange = wks.Range(srange).Select


     Select Case wks.Cells(x, "R").Value

      Case "O"
            CellRange.Interior.Color = RGB(255, 192, 0)

      Case "D"
            CellRange.Interior.Color = RGB(255, 255, 0)
      Case "C"
        If wks.Cells(x, "Y") >= 0 Then
            CellRange.Interior.Color = RGB(146, 208, 80)
        Else
            CellRange.Interior.Color = RGB(255, 0, 0)
        End If
      Case "W"
            CellRange.Interior.Color = RGB(0, 176, 240)
     End Select
    Next x
    ScreenUpdating = True

End Function

【问题讨论】:

  • 去掉末尾的.Select。
  • @WaiHaLee 如果 OP 想要一个实际的答案,我会的。他们投票不是因为“窃取”我的答案,而是因为他们是 cmets 而不是答案。如果他们把他们的 cmets 放在他们所属的地方并删除他们的答案,他们就会拿回他们的代表点数。

标签: vba excel range


【解决方案1】:

根据我的评论,它得到了太多的赞誉,改变这个:

Set CellRange = wks.Range(srange).Select

收件人:

Set CellRange = wks.Range(srange)

删除.Select。不使用.Select 函数设置范围对象。只需将范围对象设置为范围即可。

【讨论】:

    【解决方案2】:

    cmets 中的 Scott 是正确的:删除末尾的 .Select。

    选择单元格不会返回任何内容。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-12-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-08-17
      相关资源
      最近更新 更多