Link to home
Start Free TrialLog in
Avatar of Rayne
RayneFlag for United States of America

asked on

Named Range VBA

Hello All,

I have a named range VBA question
Is it possible via VBA to go across a specific row (row  = 4) and find the leftmost and rightmost cells and then create name range “myRng” with those cells – I am looking for a VBA way of doing this…

Thank you
namedRangeCreateHow.xlsx
Avatar of Rayne
Rayne
Flag of United States of America image

ASKER

so for cell range C1: C4, create the named range via VBA
But first locate the leftmost and rightmost cells in row 4
Avatar of Rayne

ASKER

I did this but still getting error
Avatar of Rayne

ASKER

Sub Button1_Click()

Dim fixedHeaderRow As Long


Dim f1, f2 As String

f1 = FirstColumn(ActiveSheet)
f2 = LastColumn(ActiveSheet)

'ActiveWorkbook.Names.Add Name:="myRng", RefersTo:="Sheet1!A2:A" & Range("A2").End(xlDown).Row

ActiveWorkbook.Names.Add Name:="myRng", RefersTo:="Sheet1!" & f1 & ":" f2




End Sub


Private Function FirstColumn(TheWorksheet As Worksheet) As String

If WorksheetFunction.CountA(TheWorksheet.Cells) > 0 Then
    FirstColumn = Replace((Cells.Find(What:="*", After:=[A1], SearchOrder:=xlByColumns, SearchDirection:=xlNext).Address), "$", "")
End If

End Function



Private Function LastColumn(TheWorksheet As Worksheet) As String
If WorksheetFunction.CountA(TheWorksheet.Cells) > 0 Then
    LastColumn = Replace((Cells.Find(What:="*", After:=[A1], SearchOrder:=xlByColumns, SearchDirection:=xlPrevious).Address), "$", "")
End If
End Function

Open in new window

Avatar of Rayne

ASKER

I am not still getting it, please assist
ASKER CERTIFIED SOLUTION
Avatar of Elton Pascua
Elton Pascua
Flag of Philippines image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
SOLUTION
Avatar of Saqib Husain
Saqib Husain
Flag of Pakistan image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of Rayne

ASKER

Hello All,

Thank you for the deferent approaches. :)

techfanatic ‘s code was complete except for he  assumed the left and right cells are C1:C4. On the other hand,, Ssaqib showed the quickest way to locate the left and right cells
 while Aebea iterated through all the cells in the header row. Good to know all the different approaches.

Thanks guys for the platinum help.
Edit: Nevermind, I misread the post.
Avatar of Rayne

ASKER