Declare PtrSafe Function GetDC Lib "user32.dll" (ByVal hwnd As Long) As LongDeclare PtrSafe Function ReleaseDC Lib "user32.dll" (ByVal hwnd As Long, ByVal hdc As Long) As LongDeclare PtrSafe Function GetDeviceCaps Lib "gdi32.dll" (ByVal hdc As Long, ByVal nIndex As Long) As Long
Const LOGPIXELSX = 88 ' 横方向のDPI取得
Function SetColumnWidthTo108Pixels() As Double
Dim hdc As Long, dpi As Double, pointWidth As Double Dim col As Range Dim pixelWidth As Double ' 設定するピクセル幅 pixelWidth = 108
' 画面のDPIを取得 hdc = GetDC(0) dpi = GetDeviceCaps(hdc, LOGPIXELSX) ReleaseDC 0, hdc ' ピクセルをポイントに変換(ポイント = ピクセル ÷ DPI × (8.08 / 0.75)) pointWidth = (pixelWidth / dpi) * (8.08 / 0.75) ' A列の幅を設定' Set col = ActiveSheet.Columns("A")' col.ColumnWidth = pointWidth SetColumnWidthTo108Pixels = pointWidth ' 結果を表示' MsgBox "A列の幅を " & pixelWidth & " ピクセル (" & Format(pointWidth, "0.00") & " ポイント) に設定しました。", vbInformation, "設定完了" End Function
Sub 列_幅()
'列幅を自動調整する
With Selection(1) If .ColumnWidth = 2 Then Selection.ColumnWidth = 200 ElseIf .ColumnWidth = 200 Then Selection.ColumnWidth = SetColumnWidthTo108Pixels Else Selection.ColumnWidth = 2 End If
End With End Sub