[英]Formating by column header instead of alphabet
I want to do some column formatting but column position is changing every time so how can i use column header instead of Column Alphabet?我想做一些列格式化,但列 position 每次都在变化,所以我如何使用列 header 而不是列字母表?
Sub Excel_Format()
Columns("J:J").Select
Selection.NumberFormat = "0"
Selection.Columns.AutoFit
End Sub
You need to start defining a Name for your column.您需要开始为列定义名称。 The quickest way to do it is to select the column (Column J in this case) and enter a name in the range/cell selector on the top-left part of your Workbook.
最快的方法是转到 select 列(在本例中为 J 列),然后在工作簿左上角的范围/单元格选择器中输入名称。 See image below:
见下图:
I have named the column to "MyColumn".我已将该列命名为“MyColumn”。 You can now use this as a reference in your code, like this:
您现在可以将其用作代码中的参考,如下所示:
Sub Excel_Format()
Dim Rng As Range
Set Rng = ActiveSheet.Range("MyColumn")
Rng.NumberFormat = "0"
Rng.Columns.AutoFit
End Sub
Even if you add or remove columns to the left of column J, the reference to MyColumn will remain correct即使您在列 J 的左侧添加或删除列,对 MyColumn 的引用仍将保持正确
Please, try the next way.请尝试下一种方法。 You can use it for any header, only adapting the used constant:
您可以将它用于任何 header,只需调整使用的常量:
Sub Excel_Format()
Dim ws As Worksheet, RngH As Range
Const myColName As String = "ColumnX" 'your column header
Set ws = ActiveSheet 'use here your necessary sheet
Set RngH = ws.rows(1).Find(myColName)
If Not RngH Is Nothing Then
With RngH.EntireColumn
.NumberFormat = "0"
.AutoFit
End With
Else
MsgBox myColName & " could not be found in the sheet first row..."
End If
End Sub
The header should exist in the first sheet row . header 应该存在于第一个工作表行中。 If not, you should adapt
ws.rows(1).Find(
writing the necessary row, instead of `...如果不是,你应该调整
ws.rows(1).Find(
写必要的行,而不是 `...
Selecting, activating in such a context only consumes Excel resources, not bringing any benefit.在这样的情况下选择、激活只会消耗Excel资源,并没有带来任何收益。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.