0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

対象範囲だけをAutoFitするExcelマクロ

Last updated at Posted at 2019-03-07

これは

選択中のセルを含む現在の範囲だけを対象にして列をAutoFitするためのマクロ。
1行目にタイトルとか書いてあるときにビヨーンとならない。
愛読している某ブログに載っていたネタを自分なりに作ってみた。

コード

Sub SmartAutoFit()
    Dim ws As Worksheet, i
    With ActiveCell.CurrentRegion
        .Select
        If MsgBox("Are you OK?", vbOKCancel, "SmartAutoFit") = vbCancel Then Exit Sub
        Application.ScreenUpdating = False
        Set ws = Workbooks.Add.Worksheets(1)
        .Copy ws.Cells(1, 1)
        ws.Columns.AutoFit
        For i = 1 To .Columns.Count
            .Columns(i).ColumnWidth = ws.Columns(i).ColumnWidth
        Next
        ws.Parent.Close False
        Application.ScreenUpdating = True
    End With
End Sub

追記

ActiveCell.CurrentRegion のところを ActiveWindow.RangeSelectionにすれば、
自分で選択したセル範囲だけを対象にするようにもできる。どちらがいいかはお好みで。

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?