简体   繁体   English

根据范围变量分配单元格值

[英]Assign cell values based on Range variable

I currently have code that copies values from several ranges, and pastes those values into other ranges. 我目前有一些代码可以复制多个范围内的值,并将这些值粘贴到其他范围内。 The scope of this project is constantly changing, so the ranges need to be changed in my VBA code every time a row or column is added. 该项目的范围不断变化,因此每次添加行或列时,都需要在我的VBA代码中更改范围。 I'm trying to streamline this by creating Global range variables to store the range locations, and have my copy/paste code reference these variables. 我试图通过创建全局范围变量来存储范围位置来简化此过程,并让我的复制/粘贴代码引用这些变量。

Public test As Range
Public def1 As Range

Public Sub initializeGlobalVars()

'Assign values to the global variables

Set def1 = Sheets("Defaults").Range("B10:D14")

Set test = Sheets("Defaults").Range("B32:D36")
test = def1

End Sub

I know i'm missing some line here or am approaching it incorrectly, but I'd like to be able to change the values of the actual cells in the variables "test" by referring to the variable "test" rather than the cell location, since it is constantly changing. 我知道我在这里缺少某些行或处理方式不正确,但是我希望能够通过引用变量“ test”而不是单元格位置来更改变量“ test”中实际单元格的值,因为它一直在变化。 Is this possible? 这可能吗?

Thank you for the help! 感谢您的帮助!

Because Range takes a string variable, you can just do something like the following: 由于Range接受字符串变量,因此您可以执行以下操作:

Dim strRangeToUse as String
strRangeToUse = "B10:D14"

Set test = Sheets("Defaults").Range(strRangeToUse)

If you then want to set another range ( strRangeToFill ) with the test range, you can do the following: 然后,如果要为测试范围设置另一个范围( strRangeToFill ),则可以执行以下操作:

Sheets("Defaults").Range(strRangeToFill).Value = test.Value

You can used TABLES , or NAMED RANGES 您可以使用TABLES或NAMED RANGES

1- Tables have a name and can be used for determine some range who is dynamic! 1-表有一个名字,可以用来确定谁是动态的范围! That way u can use ActiveSheet.ListObjects("table").range() 这样,您可以使用ActiveSheet.ListObjects(“ table”)。range()

这是桌子

2- You can Create a named range 2-您可以创建一个命名范围

That way you can use 这样你就可以使用

Range("RAGEDNUMBERONE") 

远程命名

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM