插入具有特殊格式的多行

时间:2018-03-29 11:09:00

标签: excel vba excel-vba

全部, 我正在尝试使用下面的代码插入具有特殊格式的单元格(所有细边框和所有粗边框)。我已经设置了一个提示对话框,然后我想要添加所有数量n行的格式。我对使用宏非常陌生,这可以帮助我解决问题!

Sub insertMultipleRows()

Dim iCountRows As Integer

iCountRows = Application.InputBox(Prompt:="How many rows do you want to add? Starting with row " _
    & ActiveCell.Row & "?", Type:=1)

'Error Handling
If iCountRows <= 0 Then End

If ActiveCell.Row < 9 Then
    MsgBox "You Cannot Insert Rows Before Line 9, Dummy!"
Else
    'Based on number of rows specified, inser these rows
    Rows(ActiveCell.Row & ":" & ActiveCell.Row + iCountRows - 1).Insert shift:=xlDown

    'Formatting
    With ActiveCell.Columns("A:AG").Select
        Selection.Borders.Weight = xlThin

        ActiveCell.Columns("A:AG").Select
        Selection.Borders(xlEdgeBottom).Weight = xlMedium

        ActiveCell.Columns("A:AG").Select
        Selection.Borders(xlEdgeTop).Weight = xlMedium

        ActiveCell.Columns("A:AG").Select
        Selection.Borders(xlEdgeRight).Weight = xlMedium
    End With
End If

End Sub

1 个答案:

答案 0 :(得分:0)

您应该将RowActiveCell.Row个号码保存在变量中,因为在您的工作表中添加更多Rows后,它会稍后更改。

此外,您应该避免使用Select,而不是使用With ActiveCell.Columns("A:AG").Select,以后再使用Selection,请使用以下内容:

With Range(Cells(StartRow + 1, "A"), Cells(StartRow + iCountRows, "AG"))

您正在使用以下代码:

Option Explicit

Sub insertMultipleRows()

Dim iCountRows As Long
Dim StartRow As Long

' save the row in a variable
StartRow = ActiveCell.Row

iCountRows = Application.InputBox(Prompt:="How many rows do you want to add? Starting with row " _
    & StartRow & "?", Type:=1)

'Error Handling
If iCountRows <= 0 Then End

If StartRow < 9 Then
    MsgBox "You Cannot Insert Rows Before Line 9, Dummy!"
Else
    Application.ScreenUpdating = False ' speed up the code's run-time

    'Based on number of rows specified, inser these rows
    Rows(StartRow + 1 & ":" & StartRow + iCountRows).Insert shift:=xlDown

    'Formatting
    With Range(Cells(StartRow + 1, "A"), Cells(StartRow + iCountRows, "AG"))
        .Borders.Weight = xlThin

        .Borders(xlEdgeBottom).Weight = xlMedium
        .Borders(xlEdgeTop).Weight = xlMedium
        .Borders(xlEdgeRight).Weight = xlMedium

        ' added these 2 lines
        .Borders(xlInsideHorizontal).Weight = xlMedium
        .Borders(xlInsideVertical).Weight = xlMedium
    End With
End If

Application.ScreenUpdating = True

End Sub