一段“老”程序

2023-10-18 12:53:01 浏览数 (1)

下面是以前经常使用的一段程序,也就是查找并返回多个与所给条件相匹配的单元格。

代码语言:javascript复制
Sub Select_All_Found()
 Dim strFind As String
 Dim rng As Range
 Dim rngFound As Range
 
 strFind = InputBox("请输入要查找的字符串:")
 If strFind = "" Then Exit Sub
 For Each rng In ActiveSheet.UsedRange
   If rng.Value Like "*" & strFind & "*" Then
     If rngFound Is Nothing Then Set rngFound = rng
     Set rngFound = Union(rngFound, rng)
   End If
 Next rng
 If rngFound Is Nothing Then Exit Sub
 rngFound.Select
 MsgBox "找到 " & rngFound.Count & " 个与 " & strFind & " 匹配的单元格."
End Sub

我们都知道,Find方法只会返回相匹配的第一个单元格,而这段程序通过使用Union方法将所有找到的单元格联起来,实现了返回多个相匹配的单元格。

稍微修改一下,想要选取工作表中所有背景色为红色的单元格,代码如下:

代码语言:javascript复制
Sub Select_All_Red_Cells()
 Dim rng As Range
 Dim rngRed As Range
 Dim i As Integer
 
 For Each rng In ActiveSheet.UsedRange
   If rng.Interior.Color = vbRed Then
     If rngRed Is Nothing Then Set rngRed = rng
     Set rngRed = Union(rngRed, rng)
     i = i   1
   End If
 Next rng
 
 If i > 0 Then
   rngRed.Select
   Set rngRed = Nothing
 Else
   MsgBox "没有满足条件的单元格.", vbOKOnly, "都不匹配"
 End If
End Sub

程序虽然“老”了点,但原理很有用,呵呵~~

0 人点赞