VBA Excel 工作表更改自动调整行
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/15431174/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
VBA Excel Worksheet Change Autofit Rows
提问by user1423997
I have this code in a standard module, which works fine:
我在一个标准模块中有这个代码,它工作正常:
Public Sub AutofitRows()
ThisWorkbook.Worksheets("Data").Cells.EntireRow.AutoFit
End Sub
Then I have this code in the Data worksheet module, which doesn't autofit all the rows for some reason:
然后我在数据工作表模块中有这个代码,由于某种原因它不会自动适应所有行:
Private Sub Worksheet_Change(ByVal Target As Range)
If Target.Address = "$B" Then
Call AutofitRows
End If
End Sub
Can somebody please explain how to correct this?
有人可以解释一下如何纠正这个问题吗?
Thanks.
谢谢。
回答by user1423997
Try below code :
试试下面的代码:
Public Sub AutofitRows()
Dim rng As Range
Set rng = ThisWorkbook.Worksheets("Data").Rows("3:3")
rng.AutoFit
End Sub
Assuming your below code resides on Worksheets("Data").Also the procedure will be called when value in cell B3 will change.
假设您的以下代码驻留在工作表(“数据”)上。此外,当单元格 B3 中的值发生变化时,将调用该过程。
Private Sub Worksheet_Change(ByVal Target As Range)
If Target.Address = "$B" Then
Call AutofitRows
End If
End Sub