在不使用“.Select”的Excel-VBA中进行编码 – 实例

我知道有很多这方面的文章,但都没有实际的例子,所以我理解为什么要避免,而不是如何使用它。

我有这张表: 在这里input图像说明

我想要做的是select我的表的数据范围,而不select标题和底部。

所以这是我提出的代码:

Dim MyDataFirstCell Dim MyDataLastCell 'Establish the Data Area ActiveSheet.Range("B1").Select ' My Table starts on Column B 'In the example the table starts at B4, but the user could change for B3, B5, etc. So I want to assure it will find the table. ActiveCell.Offset(1, 0).Select Do While IsEmpty(ActiveCell) DoEvents ActiveCell.Offset(1, 0).Select Loop 'The first cell (Header) has been found. I need to select the first cel of my data, so: ActiveCell.Offset(1, 0).Select DoEvents MyDataFirstCell = ActiveCell.Address 'Get the first cell address of Data Area 'Now I need to select the last cell of my table: Selection.End(xlDown).Select 'Get to Bottom Row of the data Selection.End(xlToRight).Select 'Get to the last Column and data cell by heading to the righthand end ActiveCell.Offset(-1, 0).Select ' Select the correct last cell MyDataLastCell = ActiveCell.Address 'Get the Cell address of the last cell of my data area 'Now I want to select this area: Range(MyDataFirstCell & ":" & MyDataLastCell).Select 

你能告诉我一个理想的方式来编码,而不使用“.Select”?

附加问题:

  • 我有一个类似的按字母顺序排列的表。 如何按照优化后的代码进行sorting?
  • 如果我有两个或三个相同的表下面,可以同时进行sorting,或者我应该为此做两个不同的macros?

谢谢你的帮助。 再次,我知道这可能是重复的,但没有任何发布真的帮助我。

结合列中的两个链接:

 Dim lastrow As Long Dim lastcolumn As Long Dim firstrow As Long Dim ws As Worksheet Dim rng As Range Set ws = ThisWorkbook.Worksheets("Sheet1") ' Change to your sheet With ws firstrow = .Cells(1, 2).End(xlDown).Row + 1 lastrow = .Cells(.Rows.Count, 2).End(xlUp).Row - 1 lastcolumn = .Cells(firstrow, .Columns.Count).End(xlToLeft).Column Set rng = .Range(.Cells(firstrow, 2), .Cells(lastrow, lastcolumn)) End With MsgBox rng.Address