为什么我的代码中总是出现错误?

时间:2018-12-01 00:16:33

标签: excel vba excel-vba

我正在尝试我的第一个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

我的目标是遍历行的最后一个单元格,找到一个具有特定日期的单元格,该单元格的右侧带有特定文本。然后它将突出显示该行中的第一个单元格并循环到下一行。我不太确定哪里出了问题以及为什么会出错。

非常感谢您的帮助

1 个答案:

答案 0 :(得分:2)

由于ws未设置为任何实际工作表,因此代码产生错误。解决方法如下:

  • 添加Option Explicit作为模块的第一行。这会让 Excel捕获任何未声明的变量
  • ws声明为以下变量 使用Dim语句键入Worksheet。还添加任何声明 我们稍后使用的其他变量-irrrgggbbb
  • 使用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