VBA to select columns with headers in excel (How to auto-fit columns with data?)
VBA to select columns with headers in excel (How to auto-fit columns with data?)
如何使用 VBA select Excel 中具有 headers 的所有列?或所有非空白的列?基本上 select 所有包含数据的列。
一种简单的方法是使用类似 range("A1").CurrentRegion
.
的方法
要寻址列:range("A1").CurrentRegion.Columns
。
关于 "selecting":这通常是无用的,只会减慢您的代码速度。永远不要 Select
除非你有充分的理由。
不确定这是否对您有用,但是如果您要 select 所有包含数据的单元格怎么办?这里有一个小宏,只需编辑范围以符合您的条件
Sub Macro1()
Dim LR As Long, cell As Range, rng As Range
With Sheets("Sheet1")
LR = .Range("G" & Rows.Count).End(xlUp).Row
For Each cell In .Range("A1:G" & LR)
If cell.Value <> "" Then
If rng Is Nothing Then
Set rng = cell
Else
Set rng = Union(rng, cell)
End If
End If
Next cell
rng.Select
End With
End Sub
使用数据自动调整列
Sub AutoFit()
Rows("1:1").SpecialCells(xlCellTypeConstants, 23).Columns.AutoFit
End Sub
或者可能
Sub AutoFitCell()
Cells.SpecialCells(xlCellTypeConstants, 23).Columns.AutoFit
End Sub
如何使用 VBA select Excel 中具有 headers 的所有列?或所有非空白的列?基本上 select 所有包含数据的列。
一种简单的方法是使用类似 range("A1").CurrentRegion
.
的方法
要寻址列:range("A1").CurrentRegion.Columns
。
关于 "selecting":这通常是无用的,只会减慢您的代码速度。永远不要 Select
除非你有充分的理由。
不确定这是否对您有用,但是如果您要 select 所有包含数据的单元格怎么办?这里有一个小宏,只需编辑范围以符合您的条件
Sub Macro1()
Dim LR As Long, cell As Range, rng As Range
With Sheets("Sheet1")
LR = .Range("G" & Rows.Count).End(xlUp).Row
For Each cell In .Range("A1:G" & LR)
If cell.Value <> "" Then
If rng Is Nothing Then
Set rng = cell
Else
Set rng = Union(rng, cell)
End If
End If
Next cell
rng.Select
End With
End Sub
使用数据自动调整列
Sub AutoFit()
Rows("1:1").SpecialCells(xlCellTypeConstants, 23).Columns.AutoFit
End Sub
或者可能
Sub AutoFitCell()
Cells.SpecialCells(xlCellTypeConstants, 23).Columns.AutoFit
End Sub