如何在文本input期间在Excel中自动调整列宽
我通常尽量避免在Excel中使用VBA,但是能够将文本input到单元格中,并使其列变宽或变窄以容纳input或删除的文本。
这当然会受到列中其他单元格中文本长度的影响。
“自动适合你键入”,我想你可以称之为。
有一个简单的方法来做到这一点在适当的处理程序?
我不确定在打字时是否有办法做到这一点。 我认为excel通常会拉伸单元视图,以在触发worksheet_change事件之前显示所有文本。
此代码将在更改后调整列的大小,并将目标移至新范围。 将其放置在工作表模块中。
Private Sub Worksheet_Change(ByVal Target As Range) Dim nextTarget As Range Set nextTarget = Range(Selection.Address) 'store the next range the user selects Target.Columns.Select 'autofit requires columns to be selected Target.Columns.AutoFit nextTarget.Select End Sub
如果你只是想做一个特定的列,你需要检查目标列如下:
Private Sub Worksheet_Change(ByVal Target As Range) Dim nextTarget As Range Set nextTarget = Range(Selection.Address) 'store the next range the user selects If Target.Column = 1 Then Target.Columns.Select 'autofit requires columns to be selected Target.Columns.AutoFit nextTarget.Select End If End Sub
我想不出办法去做你所要求的事情,但是有一些东西非常接近你的需要。 在现代版本的Excel(2010+,我不知道2007版本)中,您可以使用以下macros调整列的大小,以便在完成在单元格中input数据后立即适应数据。
Private Sub Workbook_SheetChange(ByVal Sh As Object, ByVal Target As Range) Application.ScreenUpdating = False ActiveSheet.Columns.AutoFit End Sub
将macros放在ThisWorkbook模块中
这将自动适合列的宽度
Private Sub Workbook_SheetChange(ByVal Sh As Object, ByVal Target As Range) Columns.AutoFit End Sub
我只是试图在表单上的前两个答案,他们没有做任何事情,idk,如果“ByVal Sh”是问题? 这是一个错字吗?
无论如何,这是我的答案,检查它,它的工作原理:
Private Sub Worksheet_Change(ByVal Target As Range) If Target Is Nothing Then Exit Sub Else With Target .Columns.Select .Columns.AutoFit End With End If End Sub
-.Reverus。