Excel宏/模块帮助 - 如何编写代码以自动调整单元格宽度

时间:2012-06-08 14:24:42

标签: excel vba module

我在这个网站上有一个用于Excel的模块/宏:[宏发送Excel内容的电子邮件] [1]宏工作,除了单元格太小,每个单元格中的大量数据,我怎么写代码中的脚本,使用单元格内的数据相应地调整单元格的宽度。细胞在数据量方面有所不同。谢谢!

Sub Send_Row()
      ' Don't forget to copy the function RangetoHTML in the module.
      ' Working in Office 2000-2010
Dim OutApp As Object
Dim OutMail As Object
Dim cell As Range
Dim rng As Range
Dim Ash As Worksheet

Set Ash = ActiveSheet
On Error GoTo cleanup
Set OutApp = CreateObject("Outlook.Application")

With Application
    .EnableEvents = False
    .ScreenUpdating = False
End With

For Each cell In Ash.Columns("B").Cells.SpecialCells(xlCellTypeConstants)
    If cell.Value Like "?*@?*.?*" And LCase(cell.Offset(0, 1).Value) = "yes" Then

        Ash.Range("A1:AE100").AutoFilter Field:=2, Criteria1:=cell.Value

        With Ash.AutoFilter.Range
            On Error Resume Next
            Set rng = .SpecialCells(xlCellTypeVisible)
            On Error GoTo 0
        End With

        Set OutMail = OutApp.CreateItem(0)

        On Error Resume Next
        With OutMail
            .To = cell.Value
            .Subject = "CSI"
            .HTMLBody = RangetoHTML(rng)
            .Display  'Or use Send
        End With
        On Error GoTo 0

        Set OutMail = Nothing
        Ash.AutoFilterMode = False
    End If
Next cell

       cleanup:
Set OutApp = Nothing
With Application
    .EnableEvents = True
    .ScreenUpdating = True
End With
      End Sub

1 个答案:

答案 0 :(得分:0)

我用

Excel.Rows.AutoFit

Excel.Columns.AutoFit

使工作表单元格自动调整为其内容的最佳高度和宽度。

您可以在代码中的任何位置调用这两行代码,但我会在创建电子邮件之前执行此操作。

作为替代方案,如果您想手动执行此操作,我会使用以下快捷键:

Alt + O + C + A - 自动调整列
Alt + O + R + A - 自动调整行