Excel 無內建斜線表頭功能,手工繪製斜線、輸入雙行標題極繁瑣。利用 VBA + 表單按鈕,實現「選取儲存格 → 點按鈕 → 輸入行/列標題 → 自動生成斜線表頭」。
Click 事件撰寫程式碼:Private Sub CommandButton1_Click()
Dim rowTitle As String, colTitle As String
Dim target As Range
' 1. 互動輸入行/列標題
rowTitle = InputBox("請輸入斜線儲存格的列標題(如:週別)", "列標題")
colTitle = InputBox("請輸入斜線儲存格的行標題(如:班級)", "行標題")
' 2. 驗證輸入
If Len(rowTitle) = 0 Or Len(colTitle) = 0 Then
MsgBox "標題不可為空!", vbExclamation
Exit Sub
End If
' 3. 確認僅選取單一儲存格
Set target = Selection
If target.CountLarge <> 1 Then
MsgBox "請僅選取一個儲存格後再執行!", vbExclamation
Exit Sub
End If
' 4. 寫入合併標題(以空格或換行分隔)
target.Value = rowTitle & " " & colTitle
' 5. 繪製左上到右下斜線
With target.Borders(xlDiagonalDown)
.LineStyle = xlContinuous
.Weight = xlThin
.ColorIndex = xlAutomatic
End With
' 6. 設定文字對齊(可選:分散對齊模擬雙行效果)
With target
.HorizontalAlignment = xlDistributed
.VerticalAlignment = xlCenter
.Orientation = 0
.WrapText = True
End With
End Sub

rowTitle & Chr(10) & colTitle 並設定 .WrapText = True + .Orientation = 45(或 -45),配合欄寬/列高手動調整,視覺更接近傳統斜線表頭。On Error GoTo ErrHandler,防止非預期中斷。