[英]Autofill the same number from column A in column B
I need to create output like the following: 我需要创建如下输出:
Column A | Column B
1. 1 1
2. 1
3. 2 2
4. 2
5. 2
So far, I have written the following code: 到目前为止,我已经编写了以下代码:
Sub ItemNum()
Dim rng As Range
Dim i As Long
Dim cell
Set rng = Range("A1:A99")
i = 1
For Each cell In rng
If (...) Then
cell.Offset(0, 1).Value = i
End If
Next
End Sub
I have already obtained the number sequence in column A. I need to add the same value in column B down to the column. 我已经获得了A列中的数字序列。我需要将B列中的相同值添加到该列中。
I would like to know how to add to increment statement. 我想知道如何添加增量声明。
Thanks 谢谢
If what you are wanting to do is place a value from column A into every cell in column B until you come to another value in Column A, then the following should work: 如果您要执行的操作是将A列中的值放入B列中的每个单元格,直到您到达A列中的另一个值,那么以下方法应该起作用:
Sub ItemNum()
Dim rng As Range
Dim i As Variant
Dim cell
Set rng = Range("A1:A99")
i = "Unknown"
For Each cell In rng
If Not IsEmpty(cell) Then
i = cell.value
End If
cell.Offset(0, 1).Value = i
Next
End Sub
You can do this without loops (quicker code): 您可以不使用循环(快速代码)来执行此操作:
Sub FastUpdate()
Dim rng1 As Range
Set rng1 = Range([a2], Cells(Rows.Count, "a").End(xlUp))
'add two rows
Set rng1 = rng1.Resize(rng1.Rows.Count + 2, 1)
'add first row
[b1].Value = [a1].Value
With rng1
.Offset(0, 1).FormulaR1C1 = "=IF(RC[-1]<>"""",RC[-1],R[-1]C)"
.Offset(0, 1).Value = .Offset(0, 1).Value
End With
End Sub
If you use a For...Next
loop instead of For...Each
loop then you can use the counter variable to address the cells in column B: 如果使用
For...Next
循环而不是For...Each
循环,则可以使用counter变量寻址B列中的单元格:
Option Explicit
Sub ItemNum()
Dim rng As Range
Dim lngCounter As Long
Dim strCellValue As String
Set rng = Range("A1:A99")
strCellValue = 0
For lngCounter = 1 To rng.Cells.Count
If rng(lngCounter, 1).Value <> "" Then
strCellValue = rng(lngCounter, 1).Value
End If
rng(lngCounter, 2).Value = strCellValue
Next
End Sub
Eg 例如
If i understand correctly, below is the answer for you. 如果我正确理解,以下是您的答案。
Assuming your data starts with A2 then Apply the below formula in B2 and drag down up to the last 假设您的数据以A2开头,然后在B2中应用以下公式,然后向下拖动到最后一个
=IF(A2<>"",A2,B1)
Note: A column data may be Number or anything. 注意:列数据可以是Number或任何数字。
Proof 证明
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.