我不断得到 'Run time error 13' 和 'mydate = Sheets("Summary").Cells(i, "A").Value'

I am constantly getting 'Run time error 13' with 'mydate = Sheets("Summary").Cells(i, "A").Value'

按照以下逻辑,代码隐藏了一些行,但它停在第 80 行并显示此错误。我检查了这些日期和时间的格式,对我来说看起来不错。 有人可以帮助找出可能出了什么问题吗?

Public Sub ShowShift3()
Dim i As Long, j As Long, lastrow1 As Long, lastrow2 As Long
Dim mydate As Date
Dim mytime As Date
Dim mystatus As String

lastrow1 = Sheets("Summary").Range("A" & Rows.Count).End(xlUp).Row
Sheets("Summary").Activate

For i = lastrow1 To i = 2 Step -1
mydate = Sheets("Summary").Cells(i, "A").Value
mytime = Sheets("Summary").Cells(i, "B").Value
If (mydate < Date) And (mytime < TimeValue("22:00:00")) Then
   Worksheets("Summary").Rows(i).Hidden = True
End If    
Next    
End Sub

错误可能出在您的数据中,而不是代码中:

Sub DateCheck()
    Dim mydate As Date
    i = 1
    mydate = Sheets("Summary").Cells(i, "A").Value
End Sub

很可能 VBA 无法将相应单元格中的值解析为日期。

检查以下内容:

Sub TestMe()
    Dim a As Date
    a = "what"
    a = ""
End Sub

"""what" 都不能转换为日期。我想在你的情况下 Cells(i, "A") 是一个空的,因此你会收到这个错误。

其他变量类型LongStringVariantObject等可以很容易地分配给空单元格的值,并且它们中的每一个都会对应解析:

  • Long 变为 0
  • String 变为 ""
  • Boolean 变为 False

如果您用以下代码替换您的代码,我相信它会按预期工作:

Public Sub ShowShift3()
Dim i As Long, j As Long, lastrow1 As Long, lastrow2 As Long
Dim mydate As Date
Dim mytime As Date
Dim mystatus As String

lastrow1 = Sheets("Summary").Range("A" & Rows.Count).End(xlUp).Row

For i = lastrow1 To 2 Step -1
    If IsDate(Sheets("Summary").Cells(i, "A").Value) = True Then 'check if the contents in the cell are in fact a date
        mydate = Sheets("Summary").Cells(i, "A").Value
        mytime = Format(Sheets("Summary").Cells(i, "B").Value, "hh:mm") 'format the time properly for comparison
        If (mydate < Date) And (mytime < TimeValue("22:00:00")) Then
            Worksheets("Summary").Rows(i).Hidden = True
        End If
    End If
Next i
End Sub