Option Explicit
Private Type POINTAPI
x As Long
y As Long
End Type
Private Declare Function GetDeviceCaps Lib "gdi32" ( _
ByVal hdc As Long, ByVal nIndex As Long) As Long
Private Declare Function GetDC Lib "user32.dll" _
(ByVal hwnd As Long) As Long
Private Declare Function ReleaseDC Lib "user32.dll" _
(ByVal hwnd As Long, ByVal hdc As Long) As Long
Private Declare Function InvalidateRect Lib "user32.dll" _
(ByVal hwnd As Long, _
ByVal lpRect As Long, _
ByVal bErase As Long) As Long
Private Declare Function GetCursorPos Lib "user32.dll" _
(ByRef lpPoint As POINTAPI) As Long
Private Const LOGPIXELSX = 88
Private Const LOGPIXELSY = 90
Private Const PointsPerInch = 72
Public Sub FitRangeToScreen(ByVal Rng As Range)
Dim tPt As POINTAPI
Dim oObj As Object
Dim oCell As Range
Dim ScrLeftToRangeRight As Variant
Dim ScrTopToRangeBottom As Variant
On Error Resume Next
Rng.Parent.Activate
Rng.Select
ActiveWindow.Zoom = True
Do
For Each oCell In Rng.Rows(1).Cells
oCell.EntireColumn.ColumnWidth = oCell.EntireColumn.ColumnWidth + 0.5
ScrLeftToRangeRight = Rng.Left + Rng.Width
With ActiveWindow
tPt.x = PTtoPX(ScrLeftToRangeRight * .Zoom / 100, False) _
+ .PointsToScreenPixelsX(0)
tPt.y = PTtoPX(Rng.Top * .Zoom / 100, True) _
+ .PointsToScreenPixelsY(0)
Set oObj = .RangeFromPoint(tPt.x, tPt.y)
End With
If TypeName(oObj) <> "Range" Then MsgBox "Width adjusted.": Exit Do
' DoEvents
Next
' DoEvents
Loop
InvalidateRect 0, 0, 0
Do
For Each oCell In Rng.Columns(1).Cells
oCell.EntireRow.RowHeight = oCell.EntireRow.RowHeight + 0.5
ScrTopToRangeBottom = Rng.Top + Rng.Height
With ActiveWindow
tPt.x = PTtoPX(Rng.Left * .Zoom / 100, False) + _
.PointsToScreenPixelsX(0)
tPt.y = PTtoPX(ScrTopToRangeBottom * .Zoom / 100, True) + _
.PointsToScreenPixelsY(0)
Set oObj = .RangeFromPoint(tPt.x, tPt.y)
End With
If TypeName(oObj) <> "Range" Then MsgBox "Height adjusted.": Exit Do
' DoEvents
Next
' DoEvents
Loop
InvalidateRect 0, 0, 0
End Sub
Private Function ScreenDPI(bVert As Boolean) As Long
Static lDPI(1), lDC
If lDPI(0) = 0 Then
lDC = GetDC(0)
lDPI(0) = GetDeviceCaps(lDC, LOGPIXELSX)
lDPI(1) = GetDeviceCaps(lDC, LOGPIXELSY)
lDC = ReleaseDC(0, lDC)
End If
ScreenDPI = lDPI(Abs(bVert))
End Function
Private Function PTtoPX _
(Points As Single, bVert As Boolean) As Long
PTtoPX = Points * ScreenDPI(bVert) / PointsPerInch
End Function