我在工作表上有以下数据集:
SheetName|ColumnIndex|Pixels
---------+-----------+------
abc |1 |50
abc |2 |150
def |1 |125
对于每张纸,我都希望使用以下内容将列宽设置为适当的像素数:
Sub setColumn (sheetName As string, columnIndex As long, pixels As long)
width=getWidthInCharacters(pixels)
ThisWorkbook.Sheets(sheetName).Cells(1, columnIndex).EntireColumn.ColumnWidth = width
End Sub
我还没有弄清楚如何编写getWidthInCharacters()
函数。如何将像素转换为字符,或者可能将.ColumnWidth
直接设置为像素?
答案 0 :(得分:2)
我很遗憾地告诉你,但根据我的经验,你不能。列宽以点为单位测量,虽然理论上可以将点转换为像素,但在分配时Excel不会非常精确地监听。从显示器到显示器,它们似乎也有所不同。基本上,点是英寸的分数,像素是屏幕上的点。对于给定特定输出设备的点,Windows有一个概念(正确或错误)。
你可以编写一个调整列宽的函数,但通常方法必须是
.ColumnWidth = dblOriginal + 0.01
。检查列宽是否已更改 - 如果有,则只需创建1-像素调整。如果没有,则需要大于0.01的数字。警告:这是可怕的,缓慢的,而不是很好的代码,如果他们在2010年之后修改了Excel版本的列宽,那么你可能很幸运,只能使用像素到点功能,转换和分配。有一些,根据我的经验,他们没有在同一台机器上的不同屏幕上给我一致的结果。真的很奇怪那一个。
答案 1 :(得分:0)
.ColumnWidth
不依赖于主题字体选择,但像素宽度确实如此:https://support.microsoft.com/en-us/kb/214123
'pixel width of column A
Debug.Print (Columns("A").Width / 72) * ThisWorkbook.WebOptions.PixelsPerInch
经过一番阅读和思考,我的解决方案:
Sub setColumnWidth(rColumnWidth As Range, iPixelWidth As Integer)
' set column width by pixels
' check status ScreenUpdating
Dim bScreenUpdatingState As Boolean
bScreenUpdatingState = Application.ScreenUpdating
' set status ScreenUpdating
If bScreenUpdatingState = True Then Application.ScreenUpdating = False
Dim iPointsPerInch As Byte
iPointsPerInch = 72
Dim iPixelsPerInch As Byte
iPixelsPerInch = ThisWorkbook.WebOptions.PixelsPerInch
' check 2 column widths: get iPointDelta
Dim rColumn As Range
Set rColumn = rColumnWidth.EntireColumn
rColumn.ColumnWidth = 1
Dim iPoint_1 As Single
iPoint_1 = rColumn.Width
rColumn.ColumnWidth = 2
Dim iPoint_2 As Single
iPoint_2 = rColumn.Width
Dim iPointDelta As Single
iPointDelta = iPoint_2 - iPoint_1
' set column width to iPixelWidth
Dim iPoint_New As Single
iPoint_New = iPixelWidth / iPixelsPerInch * iPointsPerInch
Dim iChar_New As Single
iChar_New = (iPoint_New - (iPointDelta - 1.5)) / iPointDelta
rColumn.ColumnWidth = iChar_New
' reset status ScreenUpdating
If bScreenUpdatingState = True Then Application.ScreenUpdating = True
End Sub
运行子setColumnWidth
:
Sub call_setColumnWidth()
Dim r As Range
Set r = ActiveSheet.Range("C1")
setColumnWidth r, 70
End Sub