[英]VBA Excel 2016 Loop through multiple ranges return offset value
问题:
K & L 列中有值,具体取决于单元格是否有一个值(数字)我想返回一个偏移值=RC[-4]
以下工作正常:
K4有值,L4有值,什么都不做。
K5有值,L5没有值,值=RC[-4]
当 L 被一个数字(这是允许的)覆盖时,我遇到了问题,但是当宏运行时 VBA 仍然覆盖该数字。 例如:
假设=RC[-4]
等于20
如果 K4 有一个值并且 L4 是10
,则跳过此单元格。 目前 VBA 会将 L4 中的值覆盖为20
从另一个角度来看:
如果 K4 <> "" And L4 = "" 然后 "=RC[-4]" 否则跳过/下一个单元格(K5/L5、K6/L6 等)
这是我想要的输出,但我的研究和知识缺乏......
Sub AccrualValue3()
Dim rng As Range
Dim Exrng As Range
Last_Row = Range("H" & Rows.Count).End(xlUp).Row - 1
Set rng = Range("K4:K" & Last_Row)
Set Exrng = Range("L4:L" & Last_Row)
For Each cell In rng
If cell.Value <> "" Then
For Each cell2 In Exrng
If cell2.Value = "" Then
cell.Offset(0, 1).Value = "=RC[-4]"
Else
cell.Offset(0, 1).Value = ""
End If
Next
End If
Next
End Sub
使用For … To
循环只计算行号更容易。 此外,您不需要第二个循环。
Option Explicit
Sub AccrualValue3()
Dim LastRow As Long
LastRow = Range("H" & Rows.Count).End(xlUp).Row - 1
Dim iRow As Long
For iRow = 4 To LastRow
If Cells(iRow, "K").Value <> "" And Cells(iRow, "L").Value = "" Then
Cells(iRow, "L").Value = Cells(iRow, "L").Offset(ColumnOffset:=-4).Value
End If
Next iRow
End Sub
或者,您可以使用.SpecialCells(xlCellTypeBlanks)
选择 L 列中的所有空单元格,并仅为这些单元格检查 K 列。 如果您有很多行,这应该会更快,因为它只检查 L 列为空的行而不是每一行。
Sub AccrualValue3ALTERNATIVE()
Dim LastRow As Long
LastRow = Range("H" & Rows.Count).End(xlUp).Row - 1
Dim EmptyCellsInColumnL As Range
Set EmptyCellsInColumnL = Range("L4:L" & LastRow).SpecialCells(xlCellTypeBlanks)
Dim Cell As Range
For Each Cell In EmptyCellsInColumnL
If Cell.Offset(ColumnOffset:=-1).Value <> "" Then
Cell.Value = Cell.Offset(ColumnOffset:=-4).Value
End If
Next Cell
End Sub
请注意,从最后使用的行中减去 1
LastRow = Range("H" & Rows.Count).End(xlUp).Row - 1
不处理最后使用的行。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.