首页 > 解决方案 > 动态增长合并单元格的高度

问题描述

我想在长度会有所不同的单元格中显示文本。单元格应容纳超过 5K 个字符。这就是我合并三个相邻单元格和三行的原因。

单元格的高度不会动态变化。

我已经实现的示例代码:

Sub pqrs(ByVal target as Range)
    Dim r as Range
    Set a = Worksheets("Sheet1").Range(B1:D3) 
    a.Value = "large text........."
    abcd.a '--- Called below Proc.
    a.Merge
End Sub

Sub abcd(ByVal target as Range)
    Dim r as Range
    Dim defaultHeight as Integer
    Dim maxtHeight as Integer
    Dim length as Integer
    Dim heightToUse as Double

    defaultHeight = 12
    maxHeight = 409
    taget.merge

    For Each r in target.Cells(1)
    length = Len(r.Value)
        If length >= 1000 and length <= 2000 Then
            heightToUse = defaultHeight + 100
            If (heightToUse > maxHeight) Then
                r.RowHeight = maxHeight
            Else
                r.RowHeight = heightToUse
            End If  
        ElseIf length > 2000 and length <= 4000 Then
            heightToUse = defaultHeight + 200
            If (heightToUse > maxHeight) Then
                r.RowHeight = maxHeight
            Else
                r.RowHeight = heightToUse
            End If  
        Else
            r.RowHeight = defaultHeight
        End If
        r.WrapText = True
    Next r
End Sub

标签: excelvbamacos

解决方案


我在您的代码中看到了多个问题。

1)“合并”不仅拼写为“合并”,正如@Jeeped指出的那样,“目标”拼写为“塔吉特”

2)Dim maxtHeight As Integer应该是Dim maxHeight As Integer

3)For Each r In target需要For Each r in target.rowsor For Each r in target.cells,或其他东西,如果没有看到你的例子,我真的无法判断。

4)您可能需要合并文本以获得我认为您想要的结果(例如,r.WrapText = True)。

当我纠正你所有的错误时,高度确实发生了变化,但我不能确定它是否真的达到了你想要的结果,因为我没有看到你的电子表格或实际数据。请更正所有这些错别字。如果代码仍然不起作用,请发布您的电子表格示例,以便我们查看实际布局和数据。


推荐阅读