I am trying to create a For/Next loop which, after a csv data import will name Columns of data in the format "Meter1, Meter 2..... up to the last used column and the last used row as these may change depending on the imported data.
For testing I have created a simple workbook with a single sheet (Sheet1) with data in 13 columns and 26 rows. I recorded a macro whilst I named "A2:A26" which gave me the following code:-
I have tried to use this code with a number of variables to loop through the columns with data, this is my effort:-
When executing the code, the correct number of named ranges are added to the name manager but the ranges they refer to are completely wrong.
This is what the range in the name manager looks like for one of the ranges "=Sheet1!32:32 & RS Sheet1!F:F & CS:Sheet1!32:32 & RE Sheet1!F:F & CE"
I am trying to substitute the numbers in the "Sheet1!R2C2:R26C2" part of the code with variables but have clearly got it horribly wrong.
I would be grateful if someone could give me some pointers on how to make this work
For testing I have created a simple workbook with a single sheet (Sheet1) with data in 13 columns and 26 rows. I recorded a macro whilst I named "A2:A26" which gave me the following code:-
VBA Code:
Sub NamingRecord()
ActiveWorkbook.Names.Add Name:="Name1", RefersToR1C1:="=Sheet1!R2C2:R26C2"
End Sub
I have tried to use this code with a number of variables to loop through the columns with data, this is my effort:-
VBA Code:
ub AutoName()
Dim RE As Integer 'End Row
Dim RS As Integer 'Start Row
Dim CE As Integer 'End Column
Dim CS As Integer 'Start Column
Dim N As Long
Dim M As Long
RS = 2 'not interested in the first row
CS = 2 'not interested in the first column
'Find the last row with data
RE = Sheets(1).Range("A1").End(xlDown).Row
'Find the last column with data
CE = Range("A" & CS).End(xlToRight).Column
For N = CS To CE 'loop range defined by variables
M = N - 1 'name variable number will be 1 less than the first column eg Column 2 named range will be Meter1
ActiveWorkbook.Names.Add Name:="Meter" & M, RefersToR1C1:= _
"=Sheet1!R & RS C & CS:R & RE C & CE" 'THIS IS THE LINE I THINK IS WRONG
Next N
End Sub
When executing the code, the correct number of named ranges are added to the name manager but the ranges they refer to are completely wrong.
This is what the range in the name manager looks like for one of the ranges "=Sheet1!32:32 & RS Sheet1!F:F & CS:Sheet1!32:32 & RE Sheet1!F:F & CE"
I am trying to substitute the numbers in the "Sheet1!R2C2:R26C2" part of the code with variables but have clearly got it horribly wrong.
I would be grateful if someone could give me some pointers on how to make this work