首页 > 解决方案 > 如何使用相关数据查找特定单元格?

问题描述

我正在尝试找到一些将在整个工作表中运行并选择所有相关单元格的宏。

我写了一些宏来找到单元格但只有一个单元格 - 它没有选择所有单元格。

Dim myRange As Range
Dim myCell As Range
Set myRange = Range("A1:GG1000")
Dim mynumer As Integer
mynumber = 7
For Each myCell In myRange
If myCell = mynumber Then

myCell.Select


End If
Next myCell

我如何运行宏并查看所有相关单元格?谢谢!

标签: excelvba

解决方案


也许尝试一些.FindNext迭代。

刚刚改编自上面的链接:

Sub Test()

Dim cl As Range, rng As Range
With ThisWorkbook.Sheets("Sheet1").Range("A1:GG1000")
    Set cl = .Find(7, LookIn:=xlValues, lookat:=xlWhole)
     If Not cl Is Nothing Then
        firstAddress = cl.Address
        Do
            If Not rng Is Nothing Then
                Set rng = Union(rng, cl)
            Else
                Set rng = cl
            End If
            Debug.Print rng.Address
            Set cl = .FindNext(cl)
        If cl Is Nothing Then
            GoTo DF
        End If
        Loop While cl.Address <> firstAddress
      End If
DF:
    rng.Select
End With

End Sub

问题真的是,你为什么要.Select一个范围?大多数情况下可以避免,并且很可能上面的代码可以修改为更干净的东西!


推荐阅读