簡體   English   中英

VBA Excel 2016 循環遍歷多個范圍返回偏移值

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM