[英]VBA for selecting a number of columns in an excel table
As I learned here (also quoted in SO ) the following code can be used to select the data-body of column 3 in Table1
:正如我在这里了解到的(也在SO 中引用),以下代码可用于选择
Table1
中第 3 列的数据体:
ActiveSheet.ListObjects("Table1").ListColumns(3).DataBodyRange.Select
I need help to select a number of columns together - say columns 3 to 5, or columns X to X+3 .我需要帮助才能一起选择多列- 例如列 3 到 5,或列 X 到 X+3 。
Using answers to this question I manged to go halfway by using actual column names:使用这个问题的答案,我设法通过使用实际的列名来中途:
Range("Table1[[Column3]:[Column5]]").Select
But I need to be able to use column numbers instead of names, as they will be the result of a function (ie columns X to X+d).但我需要能够使用列号而不是名称,因为它们将是函数的结果(即列 X 到 X+d)。
For a contiguous range, simply resize a single column.对于连续范围,只需调整单个列的大小。
ActiveSheet.ListObjects("Table1").ListColumns(3).DataBodyRange.Resize(, 3).Select
For a more complex selection, use Union to collect them prior to the .Select process.对于更复杂的选择,在 .Select 过程之前使用 Union 来收集它们。
With ActiveSheet.ListObjects("Table1")
Union(.ListColumns(3).DataBodyRange, _
.ListColumns(4).DataBodyRange, _
.ListColumns(5).DataBodyRange).Select
End With
See How to avoid using Select in Excel VBA macros for better methods.请参阅如何避免在 Excel VBA 宏中使用 Select 以获得更好的方法。
Use Columns method on DataBodyRange which can take a relative table range such as "A:B"
在 DataBodyRange 上使用 Columns 方法,该方法可以采用相对表范围,例如
"A:B"
So if you wanted the first two columns you could write: ActiveSheet.ListObjects("Table1").DataBodyRange.Columns("A:B").Select
因此,如果您想要前两列,您可以编写:
ActiveSheet.ListObjects("Table1").DataBodyRange.Columns("A:B").Select
But what if you wanted to select based on a relative column number?但是,如果您想根据相对列号进行选择怎么办? Create a few functions to convert numbers to this string:
创建一些函数来将数字转换为这个字符串:
Sub selectMultipe()
ActiveSheet.ListObjects("Table1").DataBodyRange.Columns(getRangeStr(1, 2)).Select
End Sub
'Get Range String
Function getRangeStr(startColNum As Long, endColNum As Long) As String
startCol = ColLtr(startColNum)
endCol = ColLtr(endColNum)
getRangeStr = startCol + ":" + endCol
End Function
'Convert column number to letter
Function ColLtr(iCol As Long) As String
If iCol > 0 And iCol <= Columns.Count Then ColLtr = Replace(Cells(1, iCol).Address(0, 0), 1, "")
End Function
Note: The column number to letter function was found here注意:列号转字母功能可在此处找到
Another way that I have used is this我使用的另一种方法是
ActiveSheet.Range("tblResult[" & .ListColumns(3).name & "]:tblResult[" & .ListColumns(.ListColumns.Count).name & "]").Select
which in this case selects column 3 and the remaining columns.在这种情况下,选择第 3 列和其余列。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.