动态范围创建

时间:2019-12-17 14:57:04

标签: excel vba

我正在尝试为动态范围创建变量引用。我的代码如下。 除了最后一行Range(startcells, Lastrow).Select以外,其他所有命令似乎都工作正常,该错误返回“范围和对象所需的方法”错误。知道为什么吗?

我认为在定义lastrow时存在问题...因为如果我单独选择startcell,那么它将起作用。

Sub colvar()

  ' select the entire column
   Dim lcol As Integer
   lcol = Sheets("A").Range("B1").Value
   Sheets("B").Activate

   Dim Lastrow As Long, i As Long, startcells As Range
   Lastrow = Cells(Rows.Count, lcol).End(xlUp).Row
   i = 6
   Set startcells = Cells(i, lcol)

   'startcells.Select
    Range(startcells, Lastrow).Select


 End Sub

1 个答案:

答案 0 :(得分:0)

您的代码中似乎缺少一个错误。这是用于创建一个包含当前工作表中所有填充单元格的新表的代码

    Dim LastRow As Long
    Dim LastColumn As Long
    Dim NewTableRange As Range

'1st you need to find your last row & column
    LastRow = ActiveSheet.Cells(ActiveSheet.Rows.Count, StartCell.Column).End(xlUp).row

   LastColumn = ActiveSheet.Cells(StartCell.row, ActiveSheet.Columns.Count).End(xlToLeft).Column

'2nd you set the need table range   
    Set NewTableRange = ActiveSheet.Range(StartCell, ActiveSheet.Cells(LastRow, LastColumn))