Skip to content

Instantly share code, notes, and snippets.

@furyutei
Last active September 2, 2020 17:48
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save furyutei/71b6973bf0f785689579a1a1be4ee2f5 to your computer and use it in GitHub Desktop.
Save furyutei/71b6973bf0f785689579a1a1be4ee2f5 to your computer and use it in GitHub Desktop.
Excelでセルの大きさをピクセル単位で設定
Option Explicit
Sub SetCellSize(WidthPixels As Long, Optional HeightPixels As Long = 0, Optional TargetRange As Range, Optional PixelsToPoints As Double = 0.75)
If HeightPixels < 1 Then HeightPixels = WidthPixels
If TargetRange Is Nothing Then Set TargetRange = ActiveSheet.Cells
Dim RefCell As Range: Set RefCell = TargetRange.Resize(1, 1)
Dim WidthOffsetPoints As Double
Dim CharWidthPoints As Double
Dim Width1 As Double
Dim Width2 As Double
Dim TargetWidthPoints As Double
Dim SetColumnWidth As Double
RefCell.ColumnWidth = 1: Width1 = RefCell.Width
RefCell.ColumnWidth = 2: Width2 = RefCell.Width
CharWidthPoints = Width2 - Width1
WidthOffsetPoints = Width1 - CharWidthPoints
TargetWidthPoints = WidthPixels * PixelsToPoints
For SetColumnWidth = (TargetWidthPoints - WidthOffsetPoints) / CharWidthPoints To TargetWidthPoints / CharWidthPoints Step 0.05
If 0 < SetColumnWidth Then
RefCell.ColumnWidth = SetColumnWidth
If TargetWidthPoints <= RefCell.Width Then Exit For
End If
Next
TargetRange.ColumnWidth = SetColumnWidth
TargetRange.RowHeight = HeightPixels * PixelsToPoints
End Sub
Sub TestSetCellSize()
'SetCellSize 100
Dim TargetRange As Range: Set TargetRange = ActiveSheet.Range("B2:D4")
SetCellSize 32, TargetRange:=TargetRange
TargetRange.Select
End Sub
@furyutei
Copy link
Author

furyutei commented Apr 3, 2020

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment