Trying to Create a bunch of named ranges using a simple loop

bisel

Board Regular
Joined
Jan 4, 2010
Messages
249
Office Version
  1. 365
Platform
  1. Windows
Hello,

I'm trying to create a bunch of named ranges and rather than manually selecting each cell, I want to use VBA to create the named ranges. Ultimately, I want to create named ranges "photo_item1" to "photo_item500" starting with cell W25

Can anyone tell me what is wrong with this macro's VBA ?

VBA Code:
Sub addnamefields()
Dim fieldname As String
Dim fieldnameroot As String

fieldnameroot = "photo_item" 

Range("W25").Select  'This is the initial (starting) cell

For i = 1 To 5
    fieldname = fieldnameroot & i
    ActiveWorkbook.Names.Add fieldname
    ActiveCell.Offset(1, 0).Select  ' Move to next cell, one row down in the same column
Next i

End Sub


Thanks,

Steve
 

Excel Facts

Format cells as currency
Select range and press Ctrl+Shift+4 to format cells as currency. (Shift 4 is the $ sign).
Try like this

VBA Code:
Sub addnamefields_v2()
  Dim fieldname As String
  Dim fieldnameroot As String
  Dim i As Long
  Dim c As Range
  
  Const Howmany As Long = 500
  
  fieldnameroot = "photo_item"
  
  For Each c In Range("W25").Resize(Howmany)
    i = i + 1
    fieldname = fieldnameroot & i
    ActiveWorkbook.Names.Add Name:=fieldname, RefersTo:=c
  Next c
End Sub
 
Upvote 0
Solution

Forum statistics

Threads
1,224,818
Messages
6,181,152
Members
453,021
Latest member
Justyna P

We've detected that you are using an adblocker.

We have a great community of people providing Excel help here, but the hosting costs are enormous. You can help keep this site running by allowing ads on MrExcel.com.
Allow Ads at MrExcel

Which adblocker are you using?

Disable AdBlock

Follow these easy steps to disable AdBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the icon in the browser’s toolbar.
2)Click on the "Pause on this site" option.
Go back

Disable AdBlock Plus

Follow these easy steps to disable AdBlock Plus

1)Click on the icon in the browser’s toolbar.
2)Click on the toggle to disable it for "mrexcel.com".
Go back

Disable uBlock Origin

Follow these easy steps to disable uBlock Origin

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back

Disable uBlock

Follow these easy steps to disable uBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back
Back
Top