试图突出显示使用的列的范围

我遇到了突出显示列使用范围的麻烦。 下面的代码创build两个工作表的副本,删除一些值,然后应该突出显示某些列。

Sub CreateAnalysisSheets() Dim cell, HlghtRng As Range Dim i As Integer Dim ref, findLast, findThis As String Dim lastRow As Long findLast = "2016" findThis = "2017" Application.ScreenUpdating = False Sheets(1).Copy After:=Sheets(2) ActiveSheet.Name = Left(Sheets(1).Name, InStr(1, Sheets(1).Name, " ")) & "Analysis" Sheets(2).Copy After:=Sheets(3) ActiveSheet.Name = Left(Sheets(2).Name, InStr(1, Sheets(2).Name, " ")) & "Analysis" Sheets("RM Analysis").Select For Each cell In ActiveSheet.UsedRange If cell.Value = "NULL" Then cell.ClearContents End If Next cell For Each cell In Range("1:1") ref = cell.Value lastRow = Range("R" & Rows.Count & "C" & cell.Column).End(xlUp).Row Set HlghtRng = Range(Cells(1, cell.Column) & Cells(lastRow, cell.Column)) If InStr(1, ref, findLast) > 0 And InStr(1, ref, "YTD") = 0 Then HlghtRng.Interior.ColorIndex = 8 End If Next cell For Each cell In Sheets(4).UsedRange If cell.Value = "NULL" Then cell.ClearContents End If Next cell Sheets("RM Analysis").Select Application.ScreenUpdating = True End Sub 

问题出现在lastRow = Range("R" & Rows.Count & "C" & cell.Column).End(xlUp).Row在哪里我得到一个Method 'Range' of Object '_Global' Failed 。 我试过寻找方法来解决这个问题,但我试过的一切( ActiveSheet.RangeSheets("RM Analysis").Range )还没有工作。

任何人都可以看到我要去哪里?

xlR1C1语法会污染您对最后一个非空白单元格的请求。

 lastRow = Cells(Rows.Count, cell.Column).End(xlUp).Row 

我强烈build议您避免依赖ActiveSheet并使用显式的父工作表引用。 使用With ... End With和前面的所有RangeCells ,可以使它变得非常简单..Range(...).Cells(...)

一旦你在With ... End With语句中, 所有的引用都必须以a开头. 。 此外,以下不是string连接(例如& ),而是作为.Range( 开始单元格逗号结束单元格 )操作。

 with worksheets("RM Analysis") ... Set HlghtRng = .Range(.Cells(1, cell.Column), .Cells(lastRow, cell.Column)) ... end with 

这应该做的

 Columns(1).Interior.ColorIndex = 3 

将列的数量更改为要高亮显示的列