我经常使用'mydate = Sheets(“Summary”)得到'运行时错误13'。单元格(i,“A”)。值'

问题描述 投票:1回答:3

根据以下逻辑,代码隐藏了一些行,但是它在第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
excel-vba error-handling runtime vba excel
3个回答
0
投票

如果您要使用以下代码替换代码,我相信它应该按预期工作:

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

1
投票

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

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

enter image description here


1
投票

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

检查以下内容:

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

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

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

  • Long成为0
  • String成为""
  • Boolean成为False
© www.soinside.com 2019 - 2024. All rights reserved.