TestAはA列の加算用でTestBはB列加算用です。 2行目から開始します。
Sub TestA()
Dim LastRowA As Long
Dim LastRowB As Long
LastRowA = Cells(Rows.Count, "A").End(xlUp).Row
LastRowB = Cells(Rows.Count, "B").End(xlUp).Row
If LastRowA > LastRowB Then
Cells(LastRowA + 1, "A").Value = WorksheetFunction.Max(Range(Cells(2, "A"), Cells(LastRowA, "A"))) + 1
Else
Cells(LastRowB + 1, "A").Value = WorksheetFunction.Max(Range(Cells(2, "A"), Cells(LastRowA, "A"))) + 1
End If
End Sub
Sub TestB()
Dim LastRowA As Long
Dim LastRowB As Long
LastRowA = Cells(Rows.Count, "A").End(xlUp).Row
LastRowB = Cells(Rows.Count, "B").End(xlUp).Row
If LastRowA > LastRowB Then
Cells(LastRowA + 1, "B").Value = WorksheetFunction.Max(Range(Cells(2, "B"), Cells(LastRowB, "B"))) + 1
Else
Cells(LastRowB + 1, "B").Value = WorksheetFunction.Max(Range(Cells(2, "B"), Cells(LastRowB, "B"))) + 1
End If
End Sub
上記で同じようなコードを一か所にしたものが以下です。
Sub TestA2()
Call CountUp("A", "B")
End Sub
Sub TestB2()
Call CountUp("B", "A")
End Sub
Sub CountUp(ByVal mCol1 As String, mCol2 As String)
Dim LastRow1 As Long
Dim LastRow2 As Long
LastRow1 = Cells(Rows.Count, mCol1).End(xlUp).Row
LastRow2 = Cells(Rows.Count, mCol2).End(xlUp).Row
If LastRow1 > LastRow2 Then
Cells(LastRow1 + 1, mCol1).Value = WorksheetFunction.Max(Range(Cells(2, mCol1), Cells(LastRow1, mCol1))) + 1
Else
Cells(LastRow2 + 1, mCol1).Value = WorksheetFunction.Max(Range(Cells(2, mCol1), Cells(LastRow1, mCol1))) + 1
End If
End Sub
Max使うのは2行目に最初の値を入れるときに1行目が文字列だった場合単に
Cells(LastRow1, mCol1) + 1
とするとエラーになるのでそれを避けるためです。他にも方法があると思いますが今回はこれで。
また今回の場合は
WorksheetFunction.Max(Range(Cells(2, mCol1), Cells(LastRow1, mCol1))) + 1
は
WorksheetFunction.Max(Cells(2, mCol1), Cells(LastRow1, mCol1)) + 1
でもいけます。