How to use indirect reference to select a single cell or range in vba

怎甘沉沦 提交于 2019-12-23 10:04:28

问题


I need simply a code for selecting a cell, however that cell to select changes. I have a cell in the workbook that will identify what cell it should be. Cell A1 contains the cell # that should be selected.

In this example cell A1 contains the word "P25", so I want the below code to reference A1 for the indirect cell ref to P25, thus select cell P25.

I tried both of these lines separately:

Sub IndirectCellSelect()

     Sheet.Range(INDIRECT(A1)).Select
     Range(INDIRECT(A1)).Select

End Sub

I get the error Sub or Function is not defined, when it gets to the word INDIRECT


回答1:


A slight alteration to the posted code works:

Range([indirect("a1")]).Select

but I would advise to try either of these instead:

Sheet.Range(Sheet.Range("A1").Value).Select
Range(Range("A1")).Select

the first being more explicit and is recommended in production code.




回答2:


You can do this a different way, but if you want to use a native Excel worksheet function within your VBA code, you need to do this like so (note that I have also adjusted how you reference A1):

Application.WorksheetFunction.Indirect(Sheets(1).Range("A1"))

Edit Apologies - I hadn't test this. It seems that the Indirect function is not available in this context. Instead, try something like this:

Dim rng as Range
Set rng = sheets(1).Range("A1")

sheets(1).Range(rng.text).Select



回答3:


Worksheets("list").Sort.SortFields.Add Key:=Range(INDIRECT("I16" & "3" & ":" & "I16" & "5002")) _
        , SortOn:=xlSortOnValues, Order:=xlAscending, DataOption:=xlSortNormal
    With Worksheets("list").Sort
        .SetRange Range("B2:K5002")
        .Header = xlYes
        .MatchCase = False
        .Orientation = xlTopToBottom
        .SortMethod = xlPinYin


来源:https://stackoverflow.com/questions/31300156/how-to-use-indirect-reference-to-select-a-single-cell-or-range-in-vba

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!