少々長くなっています。
この処理の考えるところは、Accessの出力シートにはマクロを書き込みづらいことです。
簡単にするために、処理用のシートを作ってみました。
処理用シートの内容
1.新規Bookを開きシートを1枚のみにする。これに結果を書きます。
2.標準モジュールに下記コードをコピーして貼り付けます。
(ツール→マクロ→Visual basic Editor で挿入→標準モジュール)
このBookは何回でも使えるように別名で保存しておきます。
使用方法は
3.Access2000からエクスポートしたシートをこのBookにコピーします。
4.ツール→マクロ→マクロ で『表の整形』を実行します。
質問に書かれていることは取りあえず全てできているはずです。
罫線はCurrentRegionでセル範囲を求め、Bordersコレクションを操作しています。
ソートは例としてA、B列で行っています。書き換えて下さい。
(Excel2000)
ここから(標準モジュールにコピーして貼り付けます)
Sub 表の整形()
'*** シート構造を検証
If Worksheets.Count <> 2 Then
MsgBox "シート枚数が処理要件に合致していません。中止します"
Exit Sub
Else
If Worksheets(1).Name = "変更後" Then
Worksheets(2).Activate
Else
Worksheets(1).Activate
End If
End If
'シートを変数に代入
Dim ws1 As Worksheet 'ワークシート(Accessから出したシート)
Dim ws2 As Worksheet 'ワークシート(罫線を引くシート)
Set ws1 = ActiveSheet
Set ws2 = Worksheets("変更後"): ws2.Range("A1").CurrentRegion.Clear
Dim rw As Long '行カウンタ
Dim col1 As Integer '列カウンタ1
Dim col2 As Integer '列カウンタ2
Dim hd As String 'セルの値(表題)
Dim dt As String 'セルの値(データ)
Dim Biko1, Biko2 As Integer '備考1,2の場所
Application.ScreenUpdating = False
'*** 表題部分を書き込む ***
With ws1
col2 = 0
col1 = 1: hd = .Cells(1, col1)
While hd <> ""
If hd <> "備考2" Then
If hd = "ランク" Then '特・A・Bの分離
col2 = col2 + 1: ws2.Cells(1, col2) = "特"
col2 = col2 + 1: ws2.Cells(1, col2) = "A"
col2 = col2 + 1: ws2.Cells(1, col2) = "B"
ElseIf hd = "備考1" Then '備考欄は備考1のみ使う
col2 = col2 + 1: ws2.Cells(1, col2) = "備考"
Biko1 = col1
Else
col2 = col2 + 1: ws2.Cells(1, col2) = .Cells(1, col1)
End If
Else
Biko2 = col1
End If
col1 = col1 + 1: hd = .Cells(1, col1)
Wend
End With
'*** データ部分を書き込む ***
With ws1
For rw = 2 To ws1.Range("A65536").End(xlUp).Row
col2 = 0
col1 = 1: hd = .Cells(1, col1)
While hd <> ""
dt = .Cells(rw, col1)
If hd <> "備考2" Then
If hd = "ランク" Then
Select Case dt '特・A・Bの分離
Case "特": ws2.Cells(rw, col2 + 1) = "○"
Case "A": ws2.Cells(rw, col2 + 2) = "○"
Case "B": ws2.Cells(rw, col2 + 3) = "○"
End Select
col2 = col2 + 3
ElseIf hd = "備考1" Then '備考1、2を結合
col2 = col2 + 1
ws2.Cells(rw, col2) = _
.Cells(rw, col1) & .Cells(rw, col1 + Biko2 - Biko1)
Else
col2 = col2 + 1
ws2.Cells(rw, col2) = .Cells(rw, col1)
End If
End If
col1 = col1 + 1: hd = .Cells(1, col1)
Wend
Next
End With
'*** 変更したシートを選択 ***
ws2.Activate: Range("A1").Select
ActiveCell.CurrentRegion.Select
'*** ソート *** 列A、Bの例
Selection.Sort Key1:=Range("A2"), Order1:=xlAscending, _
Key2:=Range("B2"), Order2:=xlAscending, Header:=xlYes
'*** 罫線を引く(Bordersコレクション) ***
Dim ks As Integer 'カウンタ
For ks = 7 To 12 'xlEdgeLeft から xlInsideHorizontal
With Selection.Borders(ks)
.LineStyle = xlContinuous
.Weight = xlThin
.ColorIndex = xlAutomatic
End With
Next
ws2.Range("A1").Select
Application.ScreenUpdating = True
End Sub
お礼
回答ありがとうございます。 >counta()関数でデータが記録された列数と行数を取得すれば、cells()やindirect()関数で最終セルが計算できるはずです。 すいません、これはどのようにやったらよいのでしょうか? マクロというかVBAですと「Range」とかでセルの位置を取得しますよね? そんな感じでできるのでしょうか?