[英]VBA Why is my macro reading column 5 instead of 3
I wrote a macro to insert a row between cells when their values are different. 我编写了一个宏,以在单元格的值不同时在单元格之间插入一行。 I have 9 columns in my data and the data starts at row 2. I want my macro to check all the values down column 3 (also known as column "C") and as it goes through, if the value changes (ie 2, 2, 2, 3, 3) it will insert a row between the changed value (ie 2, 2, 2, INSERT ROW, 3, 3).
我的数据中有9列,并且数据从第2行开始。我希望宏检查第3列(也称为“ C”列)下的所有值,并检查该值是否发生变化(即2)。 2、2、3、3),它将在更改后的值之间插入一行(即2、2、2,INSERT ROW,3、3)。 The problem is, my macro is reading column 5(E) not 3(C).
问题是,我的宏正在读取第5(E)列而不是3(C)。 What is wrong with it, I can't figure it out!
这有什么问题,我无法弄清楚! The reason I know this too is because I placed a msgbox to spit the value of the cell and it matches everything in column 5 but not 3. Here is my code:
我也知道这一点的原因是因为我放置了一个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
is a relative reference. DividerRange(k + counter, 3).Value
值是相对引用。 DividerRange
is a range starting at C2
, so when you ask for the (i,j)
th cell, ie (i,3)
you get something from column E where j
th columns would be: (C = 1, D = 2, E = 3) DividerRange
是从C2
开始的范围,因此当您请求第(i,j)
个单元格(即(i,3)
您会从E列中得到一些信息,其中第j
列为:(C = 1,D = 2, E = 3)
You can simplify it quite a lot, there's no need for the Range or Range count, or counter: 您可以简化很多,不需要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.