我需要创建如下输出:
Column A | Column B
1. 1 1
2. 1
3. 2 2
4. 2
5. 2
到目前为止,我编写了以下代码:
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
我已经在A栏中获得了数字序列。我需要将B列中的相同值添加到列中。
我想知道如何添加到增量语句。
由于
答案 0 :(得分:1)
如果您想要做的是将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
答案 1 :(得分:1)
你可以不用循环(更快的代码)来做到这一点:
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
答案 2 :(得分:0)
如果使用For...Next
循环而不是For...Each
循环,则可以使用计数器变量来寻址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。
答案 3 :(得分:0)