我正在尝试我的第一个VBA代码,但是在代码中的这个特定位置,我一直遇到运行时错误:
lastrow = ws.Cells(Rows.Count, 1).End(xlUp).Row
这是实际的代码:
Sub Test_loop()
' Testing loop for highlighting
Dim lastrow As Long
Dim datevar As String
lastrow = ws.Cells(Rows.Count, 1).End(xlUp).Row
For i = 2 To lastrow
datevar = Format(ws.Cells(i, 2), "mm/dd")
If ws.Cells(i, 3) = "Received" And datevar = "11/24" Then
Cells(i, 1).Interior.Color = RGB(rrr, ggg, bbb)
End If
Next i
End Sub
我的目标是遍历行的最后一个单元格,找到一个具有特定日期的单元格,该单元格的右侧带有特定文本。然后它将突出显示该行中的第一个单元格并循环到下一行。我不太确定哪里出了问题以及为什么会出错。
非常感谢您的帮助
答案 0 :(得分:2)
由于ws
未设置为任何实际工作表,因此代码产生错误。解决方法如下:
Option Explicit
作为模块的第一行。这会让
Excel捕获任何未声明的变量ws
声明为以下变量
使用Dim
语句键入Worksheet。还添加任何声明
我们稍后使用的其他变量-i
,rrr
,ggg
,bbb
ws
语句使Set
指向实际的工作表将其放在一起可以得到:
Option Explicit
Sub Test_loop()
' Testing loop for highlighting
Dim lastrow As Long
Dim datevar As String
' These variables weren't declared in the original code
Dim ws As Worksheet
Dim i As Integer
Dim rrr As Integer
Dim ggg As Integer
Dim bbb As Integer
' ws needs to be set to an actual sheet - Sheet1 is used here
' but replace this with the name of the actual sheet you need
'
' ws will be set to the worksheet called Sheet1 in whichever
' workbook is active when the code runs - this might not be
' the same workbook that the code is stored in
Set ws = Worksheets("Sheet1")
' For consistency, need to qualify Rows.Count with
' a worksheet
lastrow = ws.Cells(ws.Rows.Count, 1).End(xlUp).Row
For i = 2 To lastrow
datevar = Format(ws.Cells(i, 2), "mm/dd")
If ws.Cells(i, 3) = "Received" And datevar = "11/24" Then
Cells(i, 1).Interior.Color = RGB(rrr, ggg, bbb)
End If
Next i
End Sub