Autofill the same number from column A in column B

牧云@^-^@ 提交于 2020-01-03 00:52:12

问题


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.

I would like to know how to add to increment statement.

Thanks


回答1:


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:

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



回答2:


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



回答3:


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:

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

E.g.




回答4:


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

=IF(A2<>"",A2,B1)

Note: A column data may be Number or anything.

Proof



来源:https://stackoverflow.com/questions/38494340/autofill-the-same-number-from-column-a-in-column-b

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!