VBA-Excel 查找并选择多个单元格
分类:Excel
from https://www.itbaoku.cn/post/694045/do
欢迎加QQ群交流
问题描述
我正在编写代码,但我被困在这个问题上,我认为这应该不太难解决,但我无法解决.
我需要我的程序找到具有特定值的所有单元格并选择它们.但是它们应该在子的末尾保持选中状态.所以我改变了一点我在网上找到的代码并写道:
Sub FindAll() With Worksheets(4).Range("a1:l500") Set c = .Find("myValue", LookIn:=xlValues) If Not c Is Nothing Then firstAddress = c.Address Do Worksheets(4).Range(c.Address).Activate Set c = .FindNext(c) Loop While Not c Is Nothing And c.Address <> firstAddress End If End With End Sub
当然它会按顺序选择它们,但它们不会保持选中状态,所以最后我只选择了最后找到的单元格
谁能帮我解决这个问题?提前致谢
推荐答案
使用 联合方法将范围收集到一个不连续的范围中,然后在离开子之前.Select它们
Sub FindAll() Dim firstAddress As String, c As Range, rALL As Range With Worksheets(4).Range("a1:l500") Set c = .Find("myValue", LookIn:=xlValues) If Not c Is Nothing Then Set rALL = c firstAddress = c.Address Do Set rALL = Union(rALL, c) Worksheets(4).Range(c.Address).Activate Set c = .FindNext(c) Loop While Not c Is Nothing And c.Address <> firstAddress End If .Activate If Not rALL Is Nothing Then rALL.Select End With End Sub