如何在不同的文本行之间添加空格

时间:2014-08-21 18:41:34

标签: excel vba

我正在寻找一种在行之间添加空格的方法。我希望它添加空格的唯一时间是文本与其上方的行不同。我遇到了一些麻烦,无法弄明白。这是我到目前为止所得到的:

Sub Spaces()
    Dim cell As Range
    Dim Text1 As String
    Dim Text2 As String
        For Each cell In Selection
    Text1 = Cells(cell, 1).Text
    Text2 = Cells(cell - 1, 1).Text
    If InStr(1, cell, "-", 1) Then
        If Cells(cell, 1) <> Cells(cell - 1, 1) Then
        Else: Cells(cell + 1, 1).EntireRow.Insert
        End If
    End If
    Next    
End Sub

我非常感谢任何关于我出错的线索。

2 个答案:

答案 0 :(得分:1)

这是我用来分隔不同管道尺寸的行的代码。

Sub blastListSort()

Range("A1").Resize(Cells.Find(What:="*", SearchOrder:=xlRows, _
      SearchDirection:=xlPrevious, LookIn:=xlValues).Row, _
      Cells.Find(What:="*", SearchOrder:=xlByColumns, _
      SearchDirection:=xlPrevious, LookIn:=xlValues).Column).Select


For rown = Selection.Rows.Count To 2 Step -1

Size = Cells(rown, 3).Value
Size2 = Cells(rown, 3).Offset(-1).Value
lastRow = Range("A" & Rows.Count).End(xlUp).Row

If Size2 <> Size Then
Cells(rown, 6).EntireRow.Select
Cells(rown, 6).EntireRow.Insert
End If


Next
End Sub

希望它有所帮助! :)

答案 1 :(得分:0)

如果不做太多改动,你可以尝试这样的事情:

Sub Spaces()
    Dim cell As Range
    Dim Text1 As String
    Dim Text2 As String
    For Each cell In Selection

        ' initialize first string
        Text1 = cell.Text

        ' initialize second string for first time through
        If Text2 = vbNullString Then Text2 = Text1

        ' perform test
        If InStr(1, Text1, "-", 1) Then
            If Text1 <> Text2 Then

                ' insert row
                cell.EntireRow.Insert
            End If
        End If

        ' set second string for next time through loop
        Text2 = Text1
    Next
End Sub