Works behind sheet but not in module

onechipshot

New Member
Joined
Jun 9, 2017
Messages
4
The following code is part of a much larger piece and does a very simple task. It does what I want except fails to create the range name "TargetR"

Based on self support the problem is probably in identifying the workbook and sheet. Please help.

Private Sub AAATest()
Dim WS As Worksheet
Dim CellName As String
Dim cell As Range
Dim RangeName As String
Dim myCell As Range
Set WS = ThisWorkbook.Worksheets("Sheet1")
Worksheets("Sheet1").Select
Set myCell = Range(ActiveCell.Address)
RangeName = "TargetR"
CellName = myCell.Offset(0, 1).Address
Set cell = Range(CellName)
ThisWorkbook.Names.Add Name:=RangeName, RefersTo:=cell
End Sub
 

Excel Facts

How to fill five years of quarters?
Type 1Q-2023 in a cell. Grab the fill handle and drag down or right. After 4Q-2023, Excel will jump to 1Q-2024. Dash can be any character.
Hi,

what about

VBA Code:
Private Sub AAATest()
Dim ws As Worksheet
Dim rngCell As Range
Dim strRangeName As String

Set ws = ThisWorkbook.Worksheets("Sheet1")
ws.Activate
Set rngCell = ActiveCell.Offset(0, 1)
strRangeName = "TargetR"
ThisWorkbook.Names.Add Name:=ThisWorkbook, RefersTo:=rngCell

Set rngCell = Nothing
Set ws = Nothing

End Sub

I would not rely on working with ActiveCell as that is somehow unpredictable from the code posted here and I would incorporate a check if that name already exists in the workbook (this sample works with the ActiveWorkbook):

VBA Code:
Sub CheckAddNamesInWorkbook()

  Dim oName As Name
  Dim strName As String
  Dim strRange As String
  
  strName = "TargetR"
  strRange = "Sheet1!$B$1:$D$20"

  For Each oName In ActiveWorkbook.Names
    If oName.Name = strName Then Exit Sub
  Next oName

  ActiveWorkbook.Names.Add Name:=strName, RefersTo:="=" & strRange

End Sub

Ciao,
Holger
 
Upvote 0

Forum statistics

Threads
1,215,432
Messages
6,124,859
Members
449,194
Latest member
HellScout

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