I am trying to create an excel macro which is probably going to end up being quite large, to make things easier I am tackling it a bit at a time. So far I have….
Sub Macro4()
'
' Test Macro
'
'Selects the product_name column by header name
Dim rngAddress As Range
Set rngAddress = Range("A1:Z1").Find("product_name")
If rngAddress Is Nothing Then
MsgBox "The product_name column was not found."
Exit Sub
End If
Range(rngAddress, rngAddress.End(xlDown)).Select
'Inserts new column to the left of the product_name column
Selection.Insert Shift:=xlToRight
'Re-selects the product_name column
Range(rngAddress, rngAddress.End(xlDown)).Select
'Copys the contents of the product_name column
Selection.Copy
Selection.Paste
End Sub
I want it to do the following….
- Search the spreadsheet for the header name ‘product_name’
- Insert a blank column to the left of the ‘product_name’ column
- Copy the contents of the ‘product_name’ column
- Paste them into the newly created blank column
- Change the header name in this new column to ‘product_name_2’
Currently it works fine up until the pasting into this newly created column, then i get a
'Run-time error '438'; - Object doesn't support this property or method'
Can anyone suggest where i am going wrong?
Your error is:
This selects from the top of the column down to just above the first blank cell. The insert shifts this portion of the column right leaving the rest where it is. When you select again you are likely to get a larger range because you have mixed two columns. The copy fails because you are then trying to copy values over the top of values.
If that does not make sense, step through your macro with F8 and see what is happening at each step.
When you understand why your current macro does not work, try this:
Note:
With Sheets("XXX")…End With.Answer to second question
The macro recorder is not good at showing how to address individual cells systematically.
The above uses
Withwhich I recommend. Notice the dot in front of Cells.The one below operates on the active sheet.
RowNum must be a number. ColNum can be a number (say 5) or a letter (say “E”).
In your case RowNum is 1 and ColNum is ColToBeCopied and ColToBeCopied + 1.
P.S.
I forgot to mention that to find the botton row of a column use:
That is move up from the bottom not down from the top.
P.S. 2
To specify a range using Cells:
The dots must match: all three or none.