I am trying to assign a single value to an entire named range.
I know this can be done by using
for each a in "Named Range"
a.value = "Value"
next a
But is there a way it can be done in a single line of code? So that I can save runtime.
You can derive an address of a named range with,
application.Names("NameOfRange").RefersToRange.Address
You may pass this to a variable or directly use them as a one-line code like,
ActiveSheet.Range(Application.names("NameOfRange").RefersToRange.Address).value = "test"
In your question, you state the following 'can be done':
for each a in "Named Range"
a.value = "Value"
next a
However, this would not work as "Named Range" is a string, not a Range.
To make it a Range, it should read:
For Each a In Range("Named Range")
a.Value = "Value"
Next a
If that works , then it could be replaced with:
Range("Named Range") = "Value"
But, that shouldn't work either , as "Named Range" is not a valid name for a range as it contains a space.
So, you've been given answers that do work, provided the named range in question is entered correctly on your sheet and you modify the code provided to match the name of the range.
In short the answer could be:
Range("A1:C3") = "Value"
if you want to specify the range by its address, or if using a named range:
Range("XXXXX") = "Value"
Where XXXXX
is replaced with the name you've given your named range.
You could (and should) also qualify the sheet name for completeness;
Sheets("ZZZZZ").Range("XXXXX") = "Value"
Where ZZZZZ
is replaced with the name of the sheet/tab, and XXXXX
with the name of your range.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.