簡體   English   中英

我不斷收到“ mydate = Sheets(“ Summary”)。Cells(i,“ A”)。Value”的“運行時錯誤13”。

[英]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很可能無法將您在相應單元格中擁有的值解析為Date。

檢查以下內容:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM