Как добавить заголовок в группу строк ниже разделенных пробелом? - PullRequest
0 голосов
/ 21 февраля 2020

У меня есть некоторые данные, как показано ниже:

A
1
2

B
1
2
3

C
1
2
3

Каждая группа, разделенная пробелом и заголовком, появляется в первой строке группы. Мне нужно добавлять заголовок в первую очередь в каждой строке ниже, например:

A1
A2

B1
B2
B3

C1
C2
C3

Я нахожу этот код, но он не работает должным образом:

Sub InsertRowBelowHeader()
    Rows(ActiveWindow.SplitRow + 1).Insert
End Sub

1 Ответ

0 голосов
/ 21 февраля 2020

Может быть что-то вроде этого:

enter image description here

Код:

Option Explicit

Sub GroupName()

Dim lRow As Long
Dim i As Long
Dim GroupName As String


lRow = Cells(Rows.Count, "A").End(xlUp).Row 'Go to last row

For i = 1 To lRow 'Loo from 1st row to last row

    If i = 1 Then 'If loop is first row

        GroupName = Cells(1, "A").Value 'Then take the value for group name

    Else

        If Cells(i, "A").Value = "" Then 'Check if cell is empty
        'If empty do nothing
        Else
            If Not IsNull(Cells(i, "A").Value) And Cells(i - 1, "A").Value = "" Then 'If current cell is not null and previous cell is not blank then
                GroupName = Cells(i, "A").Value 'take the group name
            Else
                Cells(i, 2).Value = GroupName & Cells(i, "A").Value 'Else print the combination of group name + cell value
            End If
        End If

    End If

Next i

Dim j As long
For j = lRow To 2 Step -1 'To delete empty spaces (row 5, row 10 in example)
    If Cells(j, "B").Value = "" And Cells(j - 1, "B").Value = "" Then
        Range(Cells(j, "A"), Cells(j, "A")).EntireRow.Delete
    End If
Next j


End Sub
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...