简体   繁体   English

Excel VBA - 选择动态单元格范围

[英]Excel VBA - select a dynamic cell range

I want to be able to dynamically select a range of cells (the heading row), where the row is 1 but the columns with be for 1 to last column, where "A" is the first Column and where "M" is the last column. 我希望能够动态选择一系列单元格(标题行),其中行为1但列为1到最后一列,其中“A”是第一列,其中“M”是最后一列柱。 I know how to find the last column, but I don't know how to modified the below range to input the first and last column as "A" and "M". 我知道如何找到最后一列,但我不知道如何修改下面的范围来输入第一列和最后一列为“A”和“M”。

 Range("A1:M1").Select

If you want to select a variable range containing all headers cells: 如果要选择包含所有标题单元格的变量范围:

Dim sht as WorkSheet
Set sht = This Workbook.Sheets("Data")

'Range(Cells(1,1),Cells(1,Columns.Count).End(xlToLeft)).Select '<<< NOT ROBUST

sht.Range(sht.Cells(1,1),sht.Cells(1,Columns.Count).End(xlToLeft)).Select

...as long as there's no other content on that row. ......只要该行上没有其他内容。

EDIT: updated to stress that when using Range(Cells(...), Cells(...)) it's good practice to qualify both Range and Cells with a worksheet reference. 编辑:更新以强调使用Range(Cells(...), Cells(...)) ,最好使用工作表参考来限定RangeCells

sub selectVar ()
    dim x,y as integer
    let srange = "A" & x & ":" & "m" & y
    range(srange).select
end sub

I think this is the simplest way. 我认为这是最简单的方法。

So it depends on how you want to pick the incrementer, but this should work: 所以它取决于你想如何选择增量器,但这应该工作:

Range("A1:" & Cells(1, i).Address).Select

Where i is the variable that represents the column you want to select (1=A, 2=B, etc.). 其中i是表示要选择的列的变量(1 = A,2 = B等)。 Do you want to do this by column letter instead? 你想用列字母来做这件事吗? We can adjust if so :) 如果是这样我们可以调整:)

If you want the beginning to be dynamic as well, you can try this: 如果你想让开头也是动态的,你可以试试这个:

Sub SelectCols()

    Dim Col1 As Integer
    Dim Col2 As Integer

    Col1 = 2
    Col2 = 4

    Range(Cells(1, Col1), Cells(1, Col2)).Select

End Sub

I like to used this method the most, it will auto select the first column to the last column being used. 我最喜欢使用这种方法,它会自动选择第一列到最后一列使用。 However, if the last cell in the first row or the last cell in the first column are empty, this code will not calculate properly. 但是,如果第一行中的最后一个单元格或第一列中的最后一个单元格为空,则此代码将无法正确计算。 Check the link for other methods to dynamically select cell range. 检查链接以了解其他方法以动态选择单元格范围。

Sub DynamicRange()
'Best used when first column has value on last row and first row has a value in the last column

Dim sht As Worksheet
Dim LastRow As Long
Dim LastColumn As Long
Dim StartCell As Range

Set sht = Worksheets("Sheet1")
Set StartCell = Range("A1")

'Find Last Row and Column
  LastRow = sht.Cells(sht.Rows.Count, StartCell.Column).End(xlUp).Row
  LastColumn = sht.Cells(StartCell.Row, sht.Columns.Count).End(xlToLeft).Column

'Select Range
  sht.Range(StartCell, sht.Cells(LastRow, LastColumn)).Select

End Sub

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM