[英]VBA Why is my macro reading column 5 instead of 3
我編寫了一個宏,以在單元格的值不同時在單元格之間插入一行。 我的數據中有9列,並且數據從第2行開始。我希望宏檢查第3列(也稱為“ C”列)下的所有值,並檢查該值是否發生變化(即2)。 2、2、3、3),它將在更改后的值之間插入一行(即2、2、2,INSERT ROW,3、3)。 問題是,我的宏正在讀取第5(E)列而不是3(C)。 這有什么問題,我無法弄清楚! 我也知道這一點的原因是因為我放置了一個msgbox來吐出單元格的值,並且它匹配第5列中的所有內容,但不匹配第3列中的所有內容。這是我的代碼:
Sub Dividers()
Dim DividerRange As Range, lastrow As Long, k As Integer, counter As Integer
lastrow = Range("C2").End(xlDown).Row
Set DividerRange = Range(Cells(2, 3), Cells(lastrow, 3))
counter = 0
For k = 2 To DividerRange.Count
MsgBox DividerRange(k + counter, 3).Value
If DividerRange(k + counter, 3).Value = DividerRange(k + counter - 1, 3).Value Then
DividerRange(k + counter, 3).EntireRow.Insert
counter = counter + 1
Else
End If
Next k
End Sub
DividerRange(k + counter, 3).Value
值是相對引用。 DividerRange
是從C2
開始的范圍,因此當您請求第(i,j)
個單元格(即(i,3)
您會從E列中得到一些信息,其中第j
列為:(C = 1,D = 2, E = 3)
您可以簡化很多,不需要Range或Range計數或計數器:
Sub Dividers()
Dim lastrow As Long, k As Integer
lastrow = Range("C2").End(xlDown).Row
For k = 2 To lastrow
If Cells(k, 3).Value <> Cells(k - 1, 3).Value Then
Cells(k, 3).EntireRow.Insert
'Now skip a row so we don't compare against the new empty row
k = k + 1
End If
Next k
End Sub
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.