在Excel VBA中重新组织列数据

时间:2017-01-19 20:12:52

标签: excel-vba syntax vba excel

我有一个excel工作簿,其数据格式如下,数百张:

December:
Item D1
January:
Item J1
Item J2
Item J3
February: 
Item F1
March:
Item M1
Item M2

我正在尝试编写一个VBA代码来浏览每个工作表,并在每个月之后在一个表中打印第一个项目。我已经能够使用' .Find'命令找到感兴趣的月份,但如何在下一行打印单元格的内容?

为了澄清,我希望下面的代码能够确定" 12月和#34;并打印"项目D1和#34;在活动单元格中,但我不知道引用下一个单元格的VBA语法。有什么建议吗?

Set month = Worksheets("Sales").Range("A:A").Find("December:", lookat:=xlPart)
ActiveCell.Value = month+1

2 个答案:

答案 0 :(得分:0)

只是一个提示,而不是完整的解决方案(并且不要使用Month作为变量,因为它是VBA函数):

Set rMonth = Columns("A:A").Find(What:="December:", LookAt:=xlPart)
Set rNextCell = rMonth.Offset(1, 0)

Worksheets("Sales").Cells(2, 3) = rMonth.Value
Worksheets("Sales").Cells(3, 3) = rNextCell.Value

答案 1 :(得分:0)

假设您希望在所有月份都这样做,以下情况应该有效:

Dim data As Variant, upper As Long
Dim x As Variant, i As Long
Dim results As New Collection
data = Worksheets("Sheet1").Range("A:A").Value
upper = UBound(data)
For i = 1 To upper
    x = data(i, 1)
    If IsEmpty(x) Then Exit For 'otherwise we'll go until the last cell in the sheet
    Select Case x
        Case "December:", "January:", "February:", "March:" 'fill in the rest of the months here
            results.Add x
            results.Add data(i + 1, 1)
    End Select
Next

'Transposing the array
Dim finalArray() As Variant
ReDim finalArray(results.Count, 0)
For i = 1 To results.Count
    finalArray(i - 1, 0) = results(i)
Next
Worksheets("Sheet2").Range("A1:A" & results.Count).Value = finalArray