Selecting dynamic range

2019-09-03 16:28发布

Is it possible to have excel dynamic select cells? I'd love to know how to make a macro that does that. I want it to select certain cells based on the value of other cells. For example, ik want to select A1 to A20. And ik want to do that by simply typing 1 in a cell and 20 in another.

I tried this code in vba

Dim example as range Set example = range ("A1:A20")

Example. Select.

It works, but i want the A1 and A20 to be changeable so i can select different ranges

Is that possible? And if not, what is the closest thing to it? Many thanks!

2条回答
混吃等死
2楼-- · 2019-09-03 16:57

I assume start row is in B1 and end row is in B2.

Set example = Range(Cells(Cells(1, 2).Value, 1), Cells(Cells(2, 2).Value, 1))
查看更多
劳资没心,怎么记你
3楼-- · 2019-09-03 17:06

It sounds like you should have two cells in that sheet that are your controls. So you would put "A1" in one cell as the starting cell, and "A20" as the ending cell in another. Let's just put them in C1 and D1 respectively.

Option Explicit
Sub MoveDataRange()
    Dim startCell As String, endCell As String
    startCell = Range("C1").Value
    endCell = Range("D1").Value
    Range(startCell, endCell).Select
    ...
End Sub

If you want the values in C1 and D1 to be dynamic, you would have to put a formula in there to do that. If you're ok with it being changed manually, I would just highlight them a different color to call attention to the macro dependency.

查看更多
登录 后发表回答