vba 将工作表和单元格设置为变量
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/9906880/
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
Setting a Sheet and cell as variable
提问by Steveng
I am new in VBA coding. Lets say I am retrieving value from Sheet3.Cell(23, 4) for a value, is there any way in the VBA code which let me set this as a variable?
我是 VBA 编码的新手。假设我正在从 Sheet3.Cell(23, 4) 检索一个值的值,VBA 代码中是否有任何方法可以让我将其设置为变量?
For example, I have changed the interface and let the value stay at Sheet4.Cell(20,1), everywhere in my code which refer to Sheet3.Cell(23, 4) need to be changed to Sheet4.Cell(20, 1). I am thinking is there any best practice for coding VBA for situation like this?
比如我改了界面,让值保持在Sheet4.Cell(20,1),代码中所有引用Sheet3.Cell(23, 4)的地方都需要改成Sheet4.Cell(20, 1) )。我在想是否有针对这种情况编写 VBA 的最佳实践?
回答by Siddharth Rout
Yes. For that ensure that you declare the worksheet
是的。为此,请确保您声明工作表
For example
例如
Previous Code
以前的代码
Sub Sample()
Dim ws As Worksheet
Set ws = Sheets("Sheet3")
Debug.Print ws.Cells(23, 4).Value
End Sub
New Code
新代码
Sub Sample()
Dim ws As Worksheet
Set ws = Sheets("Sheet4")
Debug.Print ws.Cells(23, 4).Value
End Sub
回答by Jerry Beaucaire
Yes, set the cell as a RANGE object one time and then use that RANGE object in your code:
是的,将单元格设置为 RANGE 对象一次,然后在您的代码中使用该 RANGE 对象:
Sub RangeExample()
Dim MyRNG As Range
Set MyRNG = Sheets("Sheet1").Cells(23, 4)
Debug.Print MyRNG.Value
End Sub
Alternately you can simply store the value of that cell in memory and reference the actual value, if that's all you really need. That variable can be Long or Double or Single if numeric, or String:
或者,您可以简单地将该单元格的值存储在内存中并引用实际值,如果这就是您真正需要的。该变量可以是 Long 或 Double 或 Single(如果是数字),或者是字符串:
Sub ValueExample()
Dim MyVal As String
MyVal = Sheets("Sheet1").Cells(23, 4).Value
Debug.Print MyVal
End Sub