在某些值之间运行IF函数时,VBA类型不匹配/运行时错误为'13'-为什么会发生这种情况?试图隐藏空的行

大家好,我目前已经写出了这段代码(未进行优化,但是如果有人可以提供帮助,也将不胜感激)。该代码隐藏了设置范围(B13至J45)之间的空行:

For i = 13 To 45
    If Cells(i, "B") & Cells(i, "C") & Cells(i, "D") & Cells(i, "E") & Cells(i, "F") & Cells(i, "G") _
    & Cells(i, "F") & Cells(i, "G") & Cells(i, "H") & Cells(i, "I") & Cells(i, "J") = "" Then
        Rows(i).EntireRow.Hidden = True
    End If
Next i

好的,这可行。它不是最好看的代码,如果有人可以帮助我对其进行优化,我将不胜感激。该问题的主要问题是,当我更改行值时,出现“类型不匹配/运行时错误” 13”错误,并且该错误无法运行。我无法为自己的生活弄清楚原因。这是我尝试运行的(字面上唯一的区别是行范围,即58到81):

For i = 58 To 81
    If Cells(i, "B") & Cells(i, "C") & Cells(i, "D") & Cells(i, "E") & Cells(i, "F") & Cells(i, "G") _
    & Cells(i, "F") & Cells(i, "G") & Cells(i, "H") & Cells(i, "I") & Cells(i, "J") = "" Then
        Rows(i).EntireRow.Hidden = True
    End If
Next i

我想我的问题分为两个部分:

  1. 为什么会发生这种情况,我该如何解决?
  2. 有没有更聪明的方法来做到这一点?

非常感谢您的宝贵时间。

VBasic2008

隐藏行

  • 相反ActiveSheet,您可能想使用类似的东西ThisWorkbook.Worksheets("Sheet1")

代码

Option Explicit

Sub Hide1()
    HideRows 13, 45
End Sub

Sub Hide2()
    HideRows 58, 61
End Sub

Sub HideRows( _
        ByVal FirstRow As Long, _
        ByVal LastRow As Long)
    Const ColsAddress As String = "B:J"
    Dim ws As Worksheet: Set ws = ActiveSheet
    Dim crg As Range: Set crg = ws.Columns(ColsAddress)
    Dim cCount As Long: cCount = crg.Columns.Count
    Dim trg As Range
    Dim i As Long
    For i = FirstRow To LastRow
        If Application.CountBlank(crg.Rows(i)) = cCount Then
            If trg Is Nothing Then
                Set trg = ws.Rows(i)
            Else
                Set trg = Union(trg, ws.Rows(i))
            End If
        End If
    Next i
    If Not trg Is Nothing Then
        trg.Rows.Hidden = True
    End If

End Sub

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章