Excel中单元格有Width和Height的属性, 这两个属性以Point为单位,但它们只是可读属性, 如果需要设置行高和列宽的话, 要用到另两个可写属性RowHeight和ColumnWidth。RowHeight属性同样以Point为单位,实际上就等于Height属性。 但ColumnWidth属性和Width属性不同,下面是ColumnWidth的说明。
ColumnWidth 属性
返回或设置指定区域中所有列的列宽。Variant 类型,可读写。
说明
一个列宽单位等于”常规”样式中一个字符的宽度。对于比例字体,则使用字符“0”(零)的宽度。
如果区域中所有列的列宽都相等,ColumnWidth 属性返回该宽度值。如果区域中的列宽不等,本属性返回 Null。
ColumnWidth属性用的是列宽单位,就是说一列的ColumnWidth值刚好就是在“常规”样式下单元格可容纳的0的个数。这个“常规”样式说的是创建这个文件时使用StandardFont属性和StandardFontSize属性的“常规”(regular)样式。例如,ColumnWidth为10的单元格,使用默认字体,可以显示非粗体、非斜体和Arial的10个“0”。Excel使用数字的个数来作为列宽单位以确保当你改变一个工作表的字体时,列会自动扩大或收缩来适应显示指定数目的字符。
单元格的宽度用列宽单位,而控件用Point单位,在定位时需要转换一下。下面是一个让单元格适应控件的例子,在这个例子中,如果按钮的宽度未占满一个或几个单元格的总宽度的话,将调整按钮所覆盖的每个单元格的宽度而最终与按钮的宽度一致。
Sub ColumnWidthFitCmdButton()Dim iCol As IntegerDim i As IntegerDim iRate As Variant' 将按钮定位到Cells(2,2)的位置 Sheet1.CommandButton1.Left = Cells(2, 2).LeftSheet1.CommandButton1.Top = Cells(2, 2).TopSheet1.CommandButton1.Height = Range(Cells(2, 2), Cells(3, 2)).Height' 找到按钮覆盖的最后一列 For i = 1 To 256If Sheet1.CommandButton1.Width < Range(Cells(2, 2), Cells(2 + i)).Width TheniCol = iExit ForEnd IfNext i' 计算比例 iRate = Range(Cells(2, 2), Cells(2 + iCol - 1)).Width / Sheet1.CommandButton1.Width' 调整每个单元格的ColumnWidth,最终是按钮的宽度和单元格的总宽度一致 For i = 0 To iCol - 1Cells(2, 2 + i).ColumnWidth = Cells(2, 2 + i).ColumnWidth / iRateNext iEnd Sub
运行之前的按钮和单元格
![](http://pubimage.360doc.com/wz/default.gif)
运行ColumnWidthFitCmdButton过程之后
![](http://pubimage.360doc.com/wz/default.gif)
正因为ColumnWidth属性,没有直接方法以Point或Pixel来完全正确地设置列的宽度。使用ActiveCell.Width/ActiveCell.ColumnWidth这个比例可以近似地调整列宽到指定的Point值,但仍然会有一些误差。
微软的帮助文件介绍了一个方法以英寸或厘米来精确设置列宽,通过循环来一步一步的调整列宽达到指定的值。但是它的示例中都使用Integer变量,没有考虑到小数点的问题,出来的结果和设定值仍然有误差。这里将定义变量修改成Variant类型,并做成传递以Point为单位的值的自定义过程,这样就可以精确的使用Point、Inch、cm或Pixel来精确地设置列宽了。Inch和Pixel到Point的转换可以参考前一篇文章。
Sub ColumnWidthInPoints(points As Variant)Dim savewidth As VariantDim lowerwidth As Variant, upwidth As Variant, curwidth As VariantDim Count As Integer ' 关闭屏幕刷新 Application.ScreenUpdating = False' 设置列宽为最大值 ActiveCell.ColumnWidth = 255' 设置lowerwidth和upperwidth变量 lowerwidth = 0upwidth = 255' 设置curwidth为最大允许值得一半 ActiveCell.ColumnWidth = 127.5curwidth = ActiveCell.ColumnWidth' 设置count为0,这样当没有找到完全匹配值时不至于无限循环 Count = 0' 如果单元格宽度与指定值不同且循环计数少于20次的时候则继续循环 While (ActiveCell.Width <> points) And (Count < 20)' 如过单元格宽度小于希望的单元格宽度 If ActiveCell.Width < points Then' 设lowerwidth为curwidth lowerwidth = curwidth' 设置单元格宽度为curwidth和upwidthd的平均值 Selection.ColumnWidth = (curwidth + upwidth) / 2' 如过单元格宽度大于希望的单元格宽度 Else' 设upwidth为curwidth upwidth = curwidth' 设置单元格宽度为curwidth和lowerwidthd的平均值 Selection.ColumnWidth = (curwidth + lowerwidth) / 2End If' 设curwidth为目前列宽 curwidth = ActiveCell.ColumnWidth' 增加计数器 Count = Count + 1WendEnd Sub