我仍然是VBA的新手,我在使用偏移范围函数循环遍历我的代码并将报表中每个范围的左上角的数据移动到左侧两列时遇到了问题。
例如,我的原始报告如下:
4101 Canada
GJ002568
4102 Mexico
GJ002566
GJ002566
4103 Newcastle
GJ002567
00001626
00001634
我需要将其格式化为:
4101 Canada GJ002568
4102 Mexico GJ002566
4102 Mexico GJ002566
4103 Newcastle GJ002567
4103 Newcastle 00001626
4103 Newcastle 00001634
工作表中的行必须是动态的,因为我不会总是知道长度,而且范围也需要也是如此,因为每个中的数量都不同。我已经编写了一个宏来帮助将名称写到最后一行,但它可以做我需要做的事情。
Sub WriteNames()
Dim LastRow As Long
LastRow = Cells(Rows.Count, 3).End(xlUp).Row 'This three references the last row in column B
Dim i As Long
For i = 2 To LastRow 'This starts at 2 because the first row is a header
If Cells(i, 1).Value = ""
Cells(i, 1).Value = Cells(i - 1, 1).Value 'The neg one ref cell above
Next i
End Sub
非常感谢任何建议或帮助!
答案 0 :(得分:0)
尝试将主键存储在数组中。
Sub writeNames()
Dim i As Long, lr As Long, arr() As Variant
With Worksheets("sheet")
lr = .Cells(.Rows.Count, "A").End(xlUp).Row
For i = 2 To lr
If CBool(Len(.Cells(i, "A").Value)) And CBool(Len(.Cells(i, "B").Value)) Then
arr = .Cells(i, "A").Resize(1, 2).Value
.Cells(i, "A").Resize(1, 2).ClearContents
ElseIf CBool(Len(.Cells(i, "A").Value)) Then
.Cells(i, "C").NumberFormat = "@"
.Cells(i, "C") = .Cells(i, "A").Value
.Cells(i, "A").Resize(1, 2) = arr
End If
Next i
With .Cells(2, "A").Resize(lr, 3)
.Sort Key1:=.Cells(1), Order1:=xlAscending, _
Orientation:=xlTopToBottom, Header:=xlNo
End With
End With
End Sub
我已经使用了基本的排序来删除“死亡”。行和格式化的列C作为文本,以保留某些条目的前导零。
原始数据