获取excel单元格的像素大小

Get size of excel cell in pixels

本文关键字:像素 excel 单元格 获取      更新时间:2023-10-16

我试图以编程方式(c++但VBA解释是OK的)获得excel单元格的像素大小。excel应用程序gui显示单元格的大小为:
宽度:8.28(160像素)高度:24.6(41像素),字体:Arial 20 pt.

使用excel范围,我可以得到:
8.3 ColumnWidth: , RowHeight: 24.6
范围宽: 96 ,高度范围 24.6

我尝试使用PointsToScreenPixelsX和PointsToScreenPixelsY为上述所有值,但他们返回的值与excel gui所说的不匹配(396为行/单元格高度,136为列宽度和224为列宽度)。

任何想法?

从点到像素的转换取决于你的DPI设置。一英寸有72个点,所以如果你有96个点,就是4/3英寸。如果你的DPI(在显示属性中)是120,那么结果是160像素。

换句话说,pixels = points * DPI / 72 .

然而,这并没有考虑到缩放。在Excel中,ActiveWindow.Zoom是一个百分比,因此例如200是正常大小的两倍。注意,UI仍然显示未缩放的像素。

OP声明:

excel应用程序gui显示单元格的大小为:

宽度:8.28(160像素)高度:24.6(41像素),字体:Arial 20 pt.

首先让我澄清一下:应用程序gui以十进制和像素测量方式显示列的宽度和高度,而不考虑字体大小、屏幕大小、缩放等。对于这些因素中的任何一个,如果Excel列宽度为8.43,它将始终被定义为64 像素。其次,我有点困惑,因为我的Excel版本(目前是2010年)和我记得的每个先前版本的标准列宽为8.43,等于64 像素;同样,15的标准行高等于20 像素,这似乎与OP的示例不匹配。

在确定了这一点之后,有人问"为什么?"一个原因是:如果你调整列宽或行高,Excel允许在离散单位,不幸的是,他们决定命名像素。也许它们在早期的版本中与像素有关,但它们看起来就像使用的单位一样随机——8.43是什么,英寸,picas, ???这是肯定的!这里,我将其命名为十进制单位

无论如何,对于所有超过1.00的列宽度,离散的像素单位是十进制单位的1/7。奇怪的是,1.00以下的列宽度被分为12个单位。因此,直到2.00十进制单位的离散宽度如下:
0.08, 0.17, 0.25, 0.33, 0.42, 0.5, 0.58, 0.67, 0.75, 0.83, 0.92, 1.00, 
1.14, 1.29, 1.43, 1.57, 1.71, 1.86, 2.00

, 2.00等于19 像素。是的,当你不相信地摇头时,我会暂停,但他们就是这样做的。

幸运的是,行高似乎更均匀,1 像素等于0.75十进制单位;10个像素等于7.50;标准行高20 像素等于15.00;等等......为了防止您需要在这些随机离散的单位之间进行转换,这里有几个VBA函数可以做到这一点:

Function ColumnWidthToPixels(ByVal ColWidth As Single) As Integer
    Select Case Round(ColWidth, 4)      ' Adjust for floating point errors
    Case Is < 0:
        ColumnWidthToPixels = ColumnWidthToPixels(ActiveSheet.StandardWidth)
    Case Is < 1:
        ColumnWidthToPixels = Round(ColWidth * 12, 0)
    Case Is <= 255:
        ColumnWidthToPixels = Round(12 + ((Int(ColWidth) - 1) * 7) _
            + Round((ColWidth - Int(ColWidth)) * 7, 0), 0)
    Case Else:
        ColumnWidthToPixels = ColumnWidthToPixels(ActiveSheet.StandardWidth)
    End Select
End Function
Function PixelsToColumnWidth(ByVal Pixels As Integer) As Single
    Select Case Pixels
    Case Is < 0:
        PixelsToColumnWidth = ActiveSheet.StandardWidth
    Case Is < 12:
        PixelsToColumnWidth = Round(Pixels / 12, 2)
    Case Is <= 1790:
        PixelsToColumnWidth = Round(1 + ((Pixels - 12) / 7), 2)
    Case Else:
        PixelsToColumnWidth = ActiveSheet.StandardWidth
    End Select
End Function

示例

本例确定活动窗口中选定单元格的高度和宽度(以像素为单位),并返回lWinWidth和lWinHeight变量中的值。

With ActiveWindow
    lWinWidth = PointsToScreenPixelsX(.Selection.Width)
    lWinHeight = PointsToScreenPixelsY(.Selection.Height)
End With