vba 如何使用间接引用在vba中选择单个单元格或范围
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/31300156/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to use indirect reference to select a single cell or range in vba
提问by Bryan
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.
我只需要一个用于选择单元格的代码,但是选择更改的单元格。我在工作簿中有一个单元格,可以确定它应该是哪个单元格。单元格 A1 包含应选择的单元格 #。
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.
在此示例中,单元格 A1 包含单词“P25”,因此我希望下面的代码将间接单元格引用的 A1 引用到 P25,从而选择单元格 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
当它到达INDIRECT这个词时,我收到错误Sub或Function is not defined
采纳答案by lori_m
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.
第一个更明确,建议在生产代码中使用。
回答by user6734313
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
回答by Grade 'Eh' Bacon
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):
您可以采用不同的方式执行此操作,但是如果您想在 VBA 代码中使用本机 Excel 工作表函数,则需要这样做(请注意,我还调整了您引用 A1 的方式):
Application.WorksheetFunction.Indirect(Sheets(1).Range("A1"))
EditApologies - 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

