今天修改一个用Excel的报表,有一个数据格是跨两列,一般单格的数据格用自动换行就可以实现自适应高度,但是跨列是不行的.查找google良久,也没发现适合的办法,一阵头痛之后,突然有了灵感,于是马上做试验,还真的实现了.先写出来,如果有困于这个问题的朋友偶然路过,或许还能有一点用处.
原理:在另外一个sheet里面利用单元格换行和自适应高度的特性,将一个试验单元格宽度设置成实际跨列单元格的宽度,然后将需要输入的字符放入该试验单元格,取得高度返回给实际跨列单元格就可以了.
以下是vb的代码
Private Sub Command1_Click()
Dim objExcel As New Excel.Application
Dim wkSheet As Excel.Worksheet
objExcel.Workbooks.Open "E:\book1.xls"
Set wkSheet = Worksheets("Sheet1")
wkSheet.Select
Dim iWidth As Double
iWidth = wkSheet.Columns("A:A").ColumnWidth + wkSheet.Columns("B:B").ColumnWidth
Set wkSheet = Worksheets("Sheet2")
wkSheet.Select
wkSheet.Columns("A:A").ColumnWidth = iWidth
Range("A1").Select
With Selection
.HorizontalAlignment = xlGeneral
.VerticalAlignment = xlCenter
.WrapText = True
.Orientation = 0
.AddIndent = False
.IndentLevel = 0
.ShrinkToFit = False
.ReadingOrder = xlContext
.MergeCells = False
End With
ActiveCell.Value = "dsfsdafsdafasfsdafsadfdsafsdafa"
Dim iHeight As Double
iHeight = ActiveCell.RowHeight
Set wkSheet = Worksheets("Sheet1")
wkSheet.Select
Range("A1:B1").Select
With Selection
.HorizontalAlignment = xlGeneral
.VerticalAlignment = xlCenter
.WrapText = True
.Orientation = 0
.AddIndent = False
.IndentLevel = 0
.ShrinkToFit = False
.ReadingOrder = xlContext
.MergeCells = True
End With
Rows("1:1").Select
Selection.RowHeight = iHeight
Range("A1:B1").Select
ActiveCell.Value = "dsfsdafsdafasfsdafsadfdsafsdafa"
objExcel.ActiveWorkbook.SaveAs "e:\book2.xls"
objExcel.AlertBeforeOverwriting = False
objExcel.Quit
End Sub