Excelでセルの大きさをピクセル単位で設定する試み(元ネタはこちら)
Last active
September 2, 2020 17:48
-
-
Save furyutei/71b6973bf0f785689579a1a1be4ee2f5 to your computer and use it in GitHub Desktop.
Excelでセルの大きさをピクセル単位で設定
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
元ネタ
参考記事