[英]VBA code issue: Using offset while looping through a range for a specific Value
我已经编写了一个 VBA 代码来循环遍历特定值的范围,选择包含该值的单元格、紧邻其上方的单元格和紧邻其下方的单元格使用偏移量。 问题是代码选择了单元格值的第一个实例为 1111 和两个偏移量(选择了 1111、紧接其上方的单元格和紧接其下方的单元格),但不为其余的范围内的指定值及其各自(紧接其上方和下方的单元格)偏移量。 请协助
编码:
Sub SelectMatchingCell()
Dim strInt As Integer
Dim rng As Range, c As Range, MyRng As Range, offsetCell1 As Range, offsetCell2 As Range
'Set range with values to be searched for matches
Set rng = ActiveSheet.Range("J3:J10555")
'Fill string variable with string of text to be matched
strInt = 1111
'Loop through each cell in range
For Each c In rng
'Check if cell value matches the string to be matched
If c.Value = strInt Then
'Check if this is the first match (new range hasn't been filled yet)
If MyRng Is Nothing Then
'Fill new range with cell
Set MyRng = c
Set offsetCell1 = MyRng.Cells.Offset(-1, 0)
Set offsetCell2 = MyRng.Cells.Offset(1, 0)
Else
'Join new matching cell together with previously found matches
Set MyRng = Application.Union(MyRng, c, offsetCell1, offsetCell2)
End If
End If
Next c
'Select entire row of each cell in new range
MyRng.Cells.Select
End Sub
您只需在第一场比赛中设置 offsetCell1 和 offsetCell2。 您还需要在 Else 语句中包含这两行。
If c.Value = strInt Then
'Check if this is the first match (new range hasn't been filled yet)
If MyRng Is Nothing Then
'Fill new range with cell
Set offsetCell1 = c.Cells.Offset(-1, 0)
Set offsetCell2 = c.Cells.Offset(1, 0)
Set MyRng = Application.Union(c, offsetCell1, offsetCell2)
Else
'Join new matching cell together with previously found matches
Set offsetCell1 = c.Cells.Offset(-1, 0)
Set offsetCell2 = c.Cells.Offset(1, 0)
Set MyRng = Application.Union(MyRng, c, offsetCell1, offsetCell2)
End If
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.