追加の行を追加する Excel VBA コード

追加の行を追加する Excel VBA コード

行を追加して書式設定するための VBA コードを Excel で作成しています。

Excel シートの最初の列のエントリ数に応じて、「i」の値を変数 (示されている 20 ではなく) にする必要があります。

Sub NextLine()

'
' AddLine Macro
' Adds Line

Dim i As Integer
i = 20

    ActiveCell.Offset(1, 0).Select '1 row down
    ActiveWindow.ScrollColumn = 4
    ActiveWindow.SmallScroll ToRight:=1
    Range("$A$1:$M$" & i).Select
    Selection.Borders(xlDiagonalDown).LineStyle = xlNone
    Selection.Borders(xlDiagonalUp).LineStyle = xlNone
    With Selection.Borders(xlEdgeLeft)
        .LineStyle = xlContinuous
        .ColorIndex = 0
        .TintAndShade = 0
        .Weight = xlHairline
    End With
    With Selection.Borders(xlEdgeTop)
        .LineStyle = xlContinuous
        .ColorIndex = 0
        .TintAndShade = 0
        .Weight = xlHairline
    End With
    With Selection.Borders(xlEdgeBottom)
        .LineStyle = xlContinuous
        .ColorIndex = 0
        .TintAndShade = 0
        .Weight = xlHairline
    End With
    With Selection.Borders(xlEdgeRight)
        .LineStyle = xlContinuous
        .ColorIndex = 0
        .TintAndShade = 0
        .Weight = xlHairline
    End With
    With Selection.Borders(xlInsideVertical)
        .LineStyle = xlContinuous
        .ColorIndex = 0
        .TintAndShade = 0
        .Weight = xlHairline
    End With
    With Selection.Borders(xlInsideHorizontal)
        .LineStyle = xlContinuous
        .ColorIndex = 0
        .TintAndShade = 0
        .Weight = xlHairline
    End With
    ActiveSheet.PageSetup.PrintArea = "$A$1:$M$" & i

End Sub

答え1

次の行を置き換えます:

i=20

と:

With ActiveSheet
    i = .Cells(.Rows.Count, "A").End(xlUp).Row 
End With

列 A にデータがある行の数をカウントします。

ちなみに、マクロをテストしましたが、行は追加されませんでした。

関連情報