我找到了这篇文章,其中包含下面使用的 API 调用。我还提醒您,您可以使用 Application.Commandbars("Ribbon").Height 获取功能区的高度。所以,在 VBA 中你会这样做:
编辑:作为对公式栏和标题高度问题的回应,我添加了一个隐藏它们的函数,获取 ActiveWindow.Height,然后显示它们并获取新的 ActiveWindow.Height 并计算差异。该函数现在在下面的行中被调用,在转换之前将高度加在一起。我认为它有效,但我没有做很多测试。
Private Declare Function GetDC Lib "user32" (ByVal hwnd As Long) As Long
Private Declare Function ReleaseDC Lib "user32" (ByVal hwnd As Long, ByVal hdc As Long) As Long
Private Declare Function GetDeviceCaps Lib "gdi32" (ByVal hdc As Long, ByVal nIndex As Long) As Long
Private Const LOGPIXELSX As Long = 88
Private Const LOGPIXELSY As Long = 90
Sub CellTopLeftPixels(rng As Excel.Range)
Dim RibbonHeight As Long
Dim TotalTop As Long
Dim TotalLeft As Long
RibbonHeight = Application.CommandBars("Ribbon").Height
TotalTop = (RibbonHeight + GetFormulaBarAndHeadingsHeight + rng.Top) * PixelsPerPointY
TotalLeft = rng.Left * PixelsPerPointX
Debug.Print "Top: "; TotalTop; " Left: "; TotalLeft
End Sub
Function GetFormulaBarAndHeadingsHeight()
Dim ActiveWindowHeightWhenHidden As Long
Dim ActiveWindowHeightWhenShown As Long
Application.DisplayFormulaBar = False
ActiveWindow.DisplayHeadings = False
ActiveWindowHeightWhenHidden = ActiveWindow.Height
Application.DisplayFormulaBar = True
ActiveWindow.DisplayHeadings = True
ActiveWindowHeightWhenShown = ActiveWindow.Height
GetFormulaBarAndHeadingsHeight = ActiveWindowHeightWhenHidden - ActiveWindowHeightWhenShown
End Function
Function PixelsPerPointX() As Double
Dim hdc As Long
Dim PixPerInchX As Long
hdc = GetDC(0)
PixPerInchX = GetDeviceCaps(hdc, LOGPIXELSX)
PixelsPerPointX = PixPerInchX / 72
ReleaseDC 0, hdc
End Function
Function PixelsPerPointY() As Double
Dim hdc As Long
Dim PixPerInchY As Long
hdc = GetDC(0)
PixPerInchY = GetDeviceCaps(hdc, LOGPIXELSY)
PixelsPerPointY = PixPerInchY / 72
ReleaseDC 0, hdc
End Function
上面的 72 是每英寸的点数。
像这样称呼它:
Sub test()
CellTopLeftPixels ActiveCell
End Sub