通过 VB.NET 以像素为单位设置 Excel 列宽
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/25795700/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Set Excel Column width in pixel via VB.NET
提问by Code Pope
Is there a way to set the columnwidth in an Excel document via VB.NET in pixels? I am using currently the following codeline:
有没有办法通过 VB.NET 在 Excel 文档中以像素为单位设置列宽?我目前正在使用以下代码行:
Sheets(i).Columns("A:A").ColumnWidth = 3.14
Another problem is that I used a macro to record the width of the column and inserted it with the above statement in my code. But when I run the code the column width is 3,42 instead of 3,14.
Can anybody help me?
另一个问题是我用宏记录了列的宽度,并在我的代码中插入了上面的语句。但是当我运行代码时,列宽是 3,42 而不是 3,14。
有谁能够帮助我?
回答by Steve
Based on this post, you can perform a calculation to convert the excel unit of measure to pixels.
根据这篇文章,您可以执行计算以将 excel 度量单位转换为像素。
Here is a snippet from that web site:
这是该网站的一个片段:
COLUMNWIDTH: One unit of column width is equal to the width of one character in the Normal style. range("A1").Columnwidth returns 8.43 characters
COLUMNWIDTH:一个单位的列宽等于一个普通样式的一个字符的宽度。range("A1").Columnwidth 返回 8.43 个字符
WIDTH: Returns or sets an object's width, in points. range("A1").width returns 48 points. 72 point/inch=.6666"=64 pixels @ 96 pixels/inch
WIDTH:返回或设置对象的宽度,以磅为单位。range("A1").width 返回 48 点。72 点/英寸=.6666"=64 像素 @ 96 像素/英寸
So...
所以...
Sub testwidth()
Sheets("sheet3").Activate
screenres = 96 '96/inch
mypoints = Sheets("sheet3").Range("A1").Width
'> returns 48 points
mychars = Sheets("sheet3").Range("A1").ColumnWidth
'> returns 8.43 chars
mypixels = (mypoints / 72) * screenres 'pixel width of column
Debug.Print mypoints, mychars, mypixels
'> returns 48 8.43 64
End Sub
The column width is 48 points or 8.43 characters or 64 pixels.
列宽为 48 磅或 8.43 个字符或 64 像素。
回答by BGD
Excel doesn't use the concept of pixels when it comes to width of the columns.
当涉及到列的宽度时,Excel 不使用像素的概念。
One unit of column width is equal to the width of one character in the Normal style as documented on MSDN here: [https://docs.microsoft.com/en-us/dotnet/api/microsoft.office.tools.excel.namedrange.columnwidth?redirectedfrom=MSDN&view=vsto-2017#Microsoft_Office_Tools_Excel_NamedRange_ColumnWidth][1]
一个单位的列宽等于正常样式中的一个字符的宽度,如 MSDN 此处所述:[ https://docs.microsoft.com/en-us/dotnet/api/microsoft.office.tools.excel。 namedrange.columnwidth?redirectedfrom=MSDN&view=vsto-2017#Microsoft_Office_Tools_Excel_NamedRange_ColumnWidth][1]
Hope this helped.
希望这有帮助。
The other way to solve this issue is to convert pixels to above mentioned character and set it.
解决此问题的另一种方法是将像素转换为上述字符并进行设置。

