首页 > 解决方案 > 使用 VBA 和 Excel 在多个列中查找匹配值

问题描述

代码执行前

代码执行后

我在 excel 中有如下所示的 VBA 代码,它允许我标记在一列或多列中包含单词“FALSE”的行,如图所示。我如何让代码仅循环行和列的乘积的次数,在这种情况下为 25(5 行 * 5 列)并在不使用 For 循环的情况下退出。

Dim myRange As Range

Dim Rc As Long
Dim Cc As Long
Dim i As Integer

Set myRange = Range("C12:G16")

Rc = myRange.Rows.Count
Cc = myRange.Columns.Count
iter = Rc * Cc


With Worksheets(1).Range("C12:G16")
Set c = .Find("False", LookIn:=xlValues)
If Not c Is Nothing Then
firstAddress = c.Address
Do
i = Cc - c.Column + 2
c.Select
Selection.Offset(0, i) = "FALSE"

Set c = .FindNext(c)
Loop While Not c Is Nothing

End If
End With

标签: excelvba

解决方案


这将动态选择您的整个使用范围,然后如果 False 存在于该行,则为您使用范围右侧的第一列中的每一行填充“False”。

Sub LabelRowsFalse()

Dim myRng As Range
Dim rngWidth As Integer
Dim nextCol As Integer
Dim rngCol As Integer

Set myRng = Sheet1.UsedRange
rngWidth = myRng.Columns.Count
rngCol = myRng.Column

With myRng
    Set c = .Find("False", LookIn:=xlValues)

    If Not c Is Nothing Then
        firstAddress = c.Address
        Cells(c.Row, (rngWidth + rngCol)).Value = "False"
        Set c = .FindNext(c)

        While c.Address <> firstAddress
            Cells(c.Row, (rngWidth + rngCol)).Value = "False"
            Set c = .FindNext(c)
        Wend

    End If
End With

MsgBox ("done")

End Sub

推荐阅读