Dim rowLast, colLast As Integer
Dim i, j As Integer
rowLast = 3
colLast = 7
MsgBox "最終行は" & rowLast & vbCrLf & _
"最終列は" & colLast
For i = 2 To rowLast
For j = 2 To colLast
'表内データ集計
Next
Next
② ①で取得した最終セルまでの範囲で「表1」「表2」の文字列をループで探す (見つからないならそのまま終了)
③ 表の名前が見つかったらオフセットで一つ下にずらす(表題の下に表があるという体)
④ 表の罫線の終わりまで探索する
⑤ 罫線の終わりのセル番地を取得する
Sub 集計_Click()
Dim rowLast, colLast As Integer
Dim tableLastCell As range
rowLast = Cells.SpecialCells(xlCellTypeLastCell).row
colLast = Cells.SpecialCells(xlCellTypeLastCell).Column
MsgBox "最終行は" & rowLast & vbCrLf & _
"最終列は" & colLast
Set tableLastCell = getTableLastCell(ActiveSheet, "表1", rowLast, colLast, 1, 0)
MsgBox tableLastCell.row
Set tableLastCell = getTableLastCell(ActiveSheet, "表2", rowLast, colLast, 1, 0)
MsgBox tableLastCell.row
End Sub
'表の最後のセル番地を取得
Function getTableLastCell(ByRef ws As Variant, ByVal tableName As String, _
ByVal rowCount As Integer, ByVal colCount As Integer, _
ByVal offsetRow As Integer, ByVal offsetCol) As range
Dim i, j As Integer
Dim rowStart, colStart As Integer
Dim rowLast, colLast As Integer
For i = 1 To rowCount
For j = 1 To colCount
If ws.Cells(i, j).Value = tableName Then
rowStart = i + offsetRow
colStart = j + offsetCol
GoTo BreakLabel
End If
Next
Next
BreakLabel:
i = rowStart
j = colStart
'表の最後のセルの行番号を取得する
While ws.Cells(i, colStart).Borders(xlEdgeBottom).LineStyle <> xlLineStyleNone
rowLast = i
i = i + 1
Wend
'表の最後のセルの列番号を取得する
While ws.Cells(rowStart, j).Borders(xlEdgeBottom).LineStyle <> xlLineStyleNone
colLast = j
j = j + 1
Wend
Set getTableLastCell = ws.Cells(rowLast, colLast)
End Function
コメント