2

如何找到某个单元格的像素绝对坐标?

我正在开发 Office 2010 插件(功能区 UI),我在功能区的新菜单中添加了一个新按钮,当按下按钮时,我想获取该单元格的屏幕位置。问题是

Globals.ThisWorkbook.Application.ActiveCell . Top / Left

只给出相对于A1电子表格角落的位置,而我想要相对于屏幕 0,0 的位置。

我发现了这个:How to get screen X and Y of an Excel 2003 cell in C#但它适用于 Office 2003,我不完全理解答案。

我使用 C# 进行开发,但 VB 也可以。

谢谢!

4

2 回答 2

4

我找到了这篇文章,其中包含下面使用的 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
于 2012-02-12T15:27:39.740 回答
4

我发现这可以在没有任何黑客的情况下工作:

    Point GetScreenPositionFromCell(Excel.Range cell, Excel.Application excel)
    {
        var wnd = excel.ActiveWindow;
        if (wnd != null)
        {
            var result = new Point
            {
                X = wnd.PointsToScreenPixelsX((int)cell.Left),
                Y = wnd.PointsToScreenPixelsY((int)cell.Top)
            };

            //cleanup
            Marshal.ReleaseComObject(wnd);
            wnd = null;

            return result;
        }

        throw new Exception("Error retrieving active Excel-window.");
    }
于 2015-02-17T08:56:25.330 回答