View Single Post
  #7   Report Post  
Posted to microsoft.public.excel.programming
Dave Peterson[_2_] Dave Peterson[_2_] is offline
external usenet poster
 
Posts: 420
Default Inserting 2 columns when cells don't match

It's not too complex <bg.

I'll add some comments.

Option Explicit
Sub testme()

'some variables.
'column variables for first column, last column and looping column
Dim iCol As Long
Dim FirstCol As Long
Dim LastCol As Long

'just to make it easier to change the worksheet name if you want.
Dim wks As Worksheet

Set wks = Worksheets("sheet1") 'ActiveSheet ???

With wks
'the first, er, leftmost, column starts in column D (column 4)
FirstCol = .Range("D2").Column '4

'the rightmost column is determined the same way you did.
'select D2 and hit End and then right arrow
'then use that cell's column number
LastCol = .Range("D2").End(xlToRight).Column


'start at the righthand column and go towards the lefthand column
'but stop looking at column E.
'Since the code looks to the column to the left of the "looping" column
'and the column to the left of column E is column D -- where you were
'stopping
For iCol = LastCol To FirstCol + 1 Step -1
'if the value in the looping column is different from the value
'directly to its left (icol compared with icol-1), then
'do the work of inserting two columns
If .Cells(2, iCol).Value < .Cells(2, iCol - 1).Value Then
.Cells(2, iCol).Resize(, 2).EntireColumn.Insert
End If
Next iCol
End With

End Sub

On 11/13/2010 11:51, Frank wrote:
Thanks you to all who responded.

To Don Guillett: Your solution works only every two steps, that is it
only insert two new columns every other time instead of every time.

To Dave Peterson: You are always the man and your solution works
perfectly. I wish I could understand your code.

Regards,


--
Dave Peterson