如果if语句为假,VBA为什么不继续循环

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

如果满足条件,我正在尝试复制某些范围。但是当语句变为 false 时,我得到了运行时错误 13:类型不匹配。如果该语句为假,那么它应该不执行任何操作,并继续再次检查下一个计数器的循环

Sub Breakdown()

Dim Filter As Worksheet
Set Filter = ThisWorkbook.Sheets("Filter")
Dim Breakdown As Worksheet
Set Breakdown = ThisWorkbook.Sheets("Breakdown")

Dim counter As Integer
Dim lr As Integer
Dim pastecounter As Integer

lr = Filter.Range("B" & Application.Rows.Count).End(xlUp).Row
pastecounter = 8

For counter = 8 To lr

 If Filter.Range("BK" & counter).Value = "For Processing" Then
  Filter.Select
  Range("BM" & counter & ":BN" & counter).Copy
  Breakdown.Select
  Range("A" & pastecounter & ":B" & pastecounter).Select
  ActiveSheet.Paste
  pastecounter = pastecounter + 1
 End If

Next counter

End Sub

vba for-loop if-statement runtime-error type-mismatch
1个回答
0
投票

我猜

Filter.Range("BK" & counter).Value
遇到了错误(比如#N/A,或者其他什么)

你最好也检查一下是否有错误,如下所示:

Option Explicit

Sub Breakdown()

    Dim Filter As Worksheet
        Set Filter = ThisWorkbook.Sheets("Filter")
    Dim Breakdown As Worksheet
        Set Breakdown = ThisWorkbook.Sheets("Breakdown")
    
        With Filter
        
            Dim lr As Long
                lr = .Cells(.Rows.Count, "B").End(xlUp).Row
            
            Dim pastecounter As Long
                pastecounter = 8
            
            Dim counter As Long
                For counter = 8 To lr
                
                    Select Case True
                        Case IsError(.Range("BK" & counter).Value)
                        
                        Case .Range("BK" & counter).Value = "For Processing"
                            .Range("BM" & counter & ":BN" & counter).Copy Breakdown.Range("A" & pastecounter)
                            pastecounter = pastecounter + 1
                    End Select
            
                Next
        End With

End Sub

我也:

  1. 使用直接引用工作表而不是那些 Select/Activesheet,这是一种危险的编码方式

  2. 将所有整数值声明为 Long,以避免处理大于 32767 的行索引时出现错误

© www.soinside.com 2019 - 2024. All rights reserved.