仅选择特定范围

时间:2018-01-19 07:55:18

标签: excel vba excel-vba

我正在尝试仅检索Excel工作表中的特定范围。

我的表格如下:

enter image description here

选择应该是4列7行。来自A3 to D9

请建议。

4 个答案:

答案 0 :(得分:2)

如果我理解正确,你会有一个被垃圾包围的特定数据区域。要选择特定范围,您需要指定左上角和右下角的单元格。在这种情况下,我会寻找特殊的单元格:粗体标题和每列下至少一个空单元格。所以试试这个:

for each c in usedrange  ' row by row so finds the top left bold cell
      if c.font.bold then exit for      ' found
next c
if c.font.bold then 
     toprow = c.row
     leftcol = c.column
endif
' now search for right col
for i=leftcol to leftcol+100
    if not cells(toprow, i).font.bold then exit for
next i
if i < leftcol + 100 then rightcol = i - 1
' now search the bottom row
bottomrow = 0
for i = leftcol to rigthcol
    for r = toprow to toprow + 500
         if cells(r, i) = vbnullstring then exit for
    next r
    if bottomrow < r then bottomrow = r
next i
' now we have all data
Range(Cells(toprow, leftcol), Cells(bottomrow, rightcol).Select

这只是一个原始的最小值,你需要添加几行来初始化变量,处理其他分支和0值等。

答案 1 :(得分:1)

你走了!

ActiveWorkbook.Worksheets("Sheet1").Range("A3:D9").Select

答案 2 :(得分:1)

你走了:

lCol = Cells(1, Columns.Count).End(xlToLeft).Column
lRow = Cells(Rows.Count, 1).End(xlUp).Row
newrange = lCol & ":" & lrow
ActiveWorkbook.Worksheets("Sheet1").Range(newrange).Select

编辑: 如果表位于工作表的中间。只需将值从1更改为所需的值即可。例如,如果row=2Column=3,则lCollrow将更改如下

lCol = Cells(**3**, Columns.Count).End(xlToLeft).Column
lRow = Cells(Rows.Count, **2**).End(xlUp).Row

答案 3 :(得分:0)

使用Find方法执行此操作的另一种方法:

Sub foo()
Dim ws As Worksheet: Set ws = Sheets("Sheet1")
'declare and set your worksheet, amend as required
LastRow = ws.Cells(ws.Rows.Count, "B").End(xlUp).Row
'get the last row with data on Column A
DateColumn = ws.Cells.Find(What:="Date").Column
'find the column which contains Date
DateRow = ws.Cells.Find(What:="Date").Row
'find the row which contains Date
QuantityRow = ws.Cells.Find(What:="Quantity").Row
'find the row which contains Quantity
ws.Range(ws.Cells(DateRow, DateColumn), ws.Cells(LastRow, QuantityColumn)).Select
End Sub