Excel 为什么我的代码总是出错?
我正在尝试我的第一个VBA代码,并且在代码中的这个特定位置不断出现运行时错误:Excel 为什么我的代码总是出错?,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
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
我的目标是遍历行的最后一个单元格,找到一个具有特定日期的单元格,该单元格的右侧有一个具有特定文本的单元格。然后它将高亮显示该行中的第一个单元格并循环到下一行。我不太确定我哪里出错了,为什么会出错
非常感谢您的帮助由于未将
ws
设置为任何实际工作表,因此代码产生错误。以下是修复此问题的方法:
- 添加
作为模块中的第一行。这将使 Excel捕获任何未声明的变量选项Explicit
- 将
声明为 使用ws
语句键入工作表。还要添加任何声明 我们稍后使用的其他变量-Dim
,i
,rrr
,ggg
bbb
- 使用
语句使Set
指向实际工作表ws
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
ws
是否在代码中的其他地方声明和设置?在访问它的任何方法/属性之前,需要将它设置为实际的工作表。不,我似乎忘记了这一点。对于这个基本问题,我很抱歉,但是我该如何设置ws?我得到的错误不是问题描述,除非您明确告诉我们您得到的是什么错误。您的屏幕上就有错误消息,但不幸的是,我们无法从这里看到该屏幕。询问时请具体说明,并提供相关详细信息,在本例中,这就是您收到的确切错误消息。你要求我们帮助你解决你的问题,让我们尽可能容易地提供帮助符合你的最大利益。