【问题标题】:Skip on Type Mismatch跳过类型不匹配
【发布时间】:2019-04-09 22:03:01
【问题描述】:

在“Value =”行中,循环中有一些实例,我会遇到类型不匹配或空单元格。

如果数据集中有错误,有人可以解释我如何使用错误测试来跳过这一步并继续我的循环吗?

谢谢!

Sub ExpDate()

Dim bRow As Double
Dim tRow As Double
Dim lCol As Double
Dim fCol As Double
Dim ListRow As Double

Dim Value As Date

With ThisWorkbook.Worksheets("Canadian")

bRow = Cells(Rows.Count, 5).End(xlUp).row
tRow = 5
fCol = 7

Do While tRow <= bRow
    lCol = Cells(tRow, Columns.Count).End(xlToLeft).Column

    Do While fCol <= lCol


        Value = Cells(tRow, fCol).Value

        ListRow = Cells(Rows.Count, 1).End(xlUp).row + 1
        Cells(ListRow, 1).Value = Value


    fCol = fCol + 1
    Loop

fCol = 7
tRow = tRow + 1
Loop


Range("A5:A1000").RemoveDuplicates Columns:=Array(1, 1), Header:=xlYes

End With

End Sub

【问题讨论】:

  • 拥有一个名为 Value 的日期变量确实不是一个好主意...
  • 使用 With 块时,应在上面包含点运算符 (.)
  • 不能对@QHarr 的评论给予足够的支持,所以我想我会重复一遍。因为它是您的 With...End With 什么都不做 - 当您运行代码并查看它造成的混乱时,让另一个工作表处于活动状态。使用 .Cells.Range 引用块内 Canadian 工作表中的单元格。

标签: excel vba loops error-handling skip


【解决方案1】:

一些事情。

您只需要检查单元格是否包含日期即可。

对整数变量使用Long 而不是Double

您的 With 语句是多余的,因为您需要在范围引用前使用点 - 我已添加它们。

Sub ExpDate()

Dim bRow As Long
Dim tRow As Long
Dim lCol As Long
Dim fCol As Long
Dim ListRow As Long
Dim Value As Date

With ThisWorkbook.Worksheets("Canadian")
    bRow = .Cells(Rows.Count, 5).End(xlUp).Row
    tRow = 5
    fCol = 7

    Do While tRow <= bRow
        lCol = .Cells(tRow, Columns.Count).End(xlToLeft).Column
        Do While fCol <= lCol
            If IsDate(.Cells(tRow, fCol).Value) Then
                ListRow = .Cells(Rows.Count, 1).End(xlUp).Row + 1
                .Cells(ListRow, 1).Value = .Cells(tRow, fCol).Value
                fCol = fCol + 1
            End If
        Loop
        fCol = 7
        tRow = tRow + 1
    Loop
    .Range("A5:A1000").RemoveDuplicates Columns:=Array(1, 1), Header:=xlYes
End With

End Sub

【讨论】:

  • 这是我的荣幸。
【解决方案2】:

假设您的输入看起来像列A,并且您想将日期传递给列B

应该考虑两个问题 - 第 3 行和第 5 行中的单元格。第 5 行可以很容易地检查,只要它是错误的,?IsError(Cells(5,1) 将返回 True。但是,如果尝试检查?IsError(Cdate("K")),就会出现问题。

修复它的快速方法是一个专用的布尔函数,其中包含On Error Resume Next,如果CDate(value) 转换中有任何特定错误,则返回True

Sub TestMe()

    Dim target As Range
    Dim myCell As Range
    Set target = Worksheets(1).Range("A1:A6")

    For Each myCell In target
        If IsCellDate(myCell) Then
            Dim someDate As Date
            someDate = myCell
            myCell.Offset(0, 1) = someDate
        End If
    Next

End Sub

Public Function IsCellDate(myData As Variant) As Boolean

    On Error Resume Next '- use this line really with caution!

    If IsError(CDate(myData)) Then
        IsCellDate = False
        Exit Function
    End If
    IsCellDate = True

End Function

或者您可以使用IsDate() 并避免使用this answer 中的自定义函数。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-06-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-06-25
    • 2020-12-03
    • 2014-01-08
    相关资源
    最近更新 更多