以文本方式查看主题

-  Foxtable(狐表)  (http://foxtable.com/bbs/index.asp)
--  专家坐堂  (http://foxtable.com/bbs/list.asp?boardid=2)
----  [求助]Excel报表中,对于合并的单元格,有什么办法自动调整行高?  (http://foxtable.com/bbs/dispbbs.asp?boardid=2&id=76034)

--  作者:ericsky
--  发布时间:2015/10/20 13:53:00
--  [求助]Excel报表中,对于合并的单元格,有什么办法自动调整行高?

Dim App As New MSExcel.Application
Dim Wb As MSExcel.WorkBook = App.WorkBooks.Open("D:\\Report.xls")
Dim Ws As MSExcel.WorkSheet = Wb.WorkSheets(1)
Dim Rg As MSExcel.Range = Ws.Cells

Rg.WrapText = True 
\'Rg.EntireColumn.AutoFit   \'自动调整列宽

Rg.EntireRow.AutoFit  \'自动调整行高
App.Visible = True


上面的VBA代码只对未合并的单元格有效,合并的单元格要如何处理呢?
请老师指点!
[此贴子已经被作者于2015/10/20 13:53:38编辑过]

--  作者:大红袍
--  发布时间:2015/10/20 14:04:00
--  

Dim App As New MSExcel.Application
try
    Dim Wb As MSExcel.WorkBook = app.WorkBooks.open("d:\\test.xls")
    Dim rg As MSExcel.Range
    Dim Ws = wb.WorkSheets(1)
    Dim tempWs = wb.WorkSheets.Add
    For Each rg In ws.UsedRange
        If rg.MergeCells Then
            Dim tempCell As MSExcel.Range
            Dim width As Double = 0
            Dim tempCol
            For Each tempcol In rg.MergeArea.Columns
                width = width + tempcol.ColumnWidth
            Next
            tempWs.Columns(1).WrapText = True
            tempWs.Columns(1).ColumnWidth = width
            tempWs.Columns(1).Font.Size = rg.Font.Size
            tempWs.Cells(1, 1).Value = rg.Value
            tempWs.Cells(1, 1).RowHeight = 0
            tempWs.Cells(1, 1).EntireRow.Activate
            tempWs.Cells(1, 1).EntireRow.AutoFit
            If (rg.RowHeight < tempWs.Cells(1, 1).RowHeight) Then
                Dim tempHeight As Double
                Dim tempCount As Integer
                tempHeight = tempWs.Cells(1, 1).RowHeight
                tempCount = rg.MergeArea.Rows.Count
                For Each addHeightRow As object In rg.MergeArea.Rows
                   
                    If (addHeightRow.RowHeight < tempHeight / tempCount) Then
                        addHeightRow.RowHeight = tempHeight / tempCount
                    End If
                    tempHeight = tempHeight - addHeightRow.RowHeight
                    tempCount = tempCount - 1
                Next
                rg.WrapText = True
            End If
        End If
    Next
    app.DisplayAlerts = False
    tempWs.Delete
    app.visible = True
catch ex As exception
    msgbox(ex.message)
    app.quit
End try


--  作者:ericsky
--  发布时间:2015/10/20 14:17:00
--  
多谢大红袍老师,让您费心了
这个代码跟我现在用的差不多,就是加单元格-自动行高-再删除
效果不是很理想,而且效率不高,生成报表都要4秒以上
有没有其他好办法?
多谢!

--  作者:大红袍
--  发布时间:2015/10/20 14:26:00
--  
没办法。
--  作者:ericsky
--  发布时间:2015/10/20 14:31:00
--  
好的,谢谢!
呼吁狐爸对此问题进行完善!
最近在报表模板上面伤透脑筋,excel,rtf,word都各有不足,没办法,得去试试专业报表。