Solved

Simple VBA Loop

Posted on 2011-02-16
11
190 Views
Last Modified: 2012-05-11
See code below.  This is my first attempt at a loop!
The precise functionality is not important.

However, note that the same process is performed on two different sheets. (Yes, I know they have bad names!).  The code is therefore duplicated.

What is the syntax to loop through 2 sheets. Perhaps the following??

Dim strSheet as string
For strSheet in  Sheets("C'YearTrendP&L-IRE(24)"), Sheets("C'tYearTrendP&L-UK(25)")

??
Sub pastey()
'
    Dim strPM1
    strPM1 = Range("PreviousMonth1")
    
    Sheets("C'YearTrendP&L-IRE(24)").Select
      
    Columns(strPM1 & ":" & strPM1).Select
    Selection.Copy
    Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
        :=False, Transpose:=False
    
    Sheets("C'tYearTrendP&L-UK(25)").Select
    Columns(strPM1 & ":" & strPM1).Select
    Selection.Copy
    Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
        :=False, Transpose:=False
    
    Sheets("IRETB(23) ").Select
    MsgBox "Finished Copying and Pasting"
End Sub

Open in new window

0
Comment
Question by:Patrick O'Dea
11 Comments
 
LVL 30

Accepted Solution

by:
SiddharthRout earned 167 total points
ID: 34911848
There is no need to loop. What you are doing can be further refined to

Sub pastey()
    Dim strPM1
    strPM1 = Range("PreviousMonth1")
    
    With Sheets("C'YearTrendP&L-IRE(24)").Columns(strPM1 & ":" & strPM1)
        .Copy
        .PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
        :=False, Transpose:=False
    End With
    
    With Sheets("C'tYearTrendP&L-UK(25)").Columns(strPM1 & ":" & strPM1)
        .Copy
        .PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
        :=False, Transpose:=False
    End With
    
    MsgBox "Finished Copying and Pasting"
End Sub

Open in new window


Sid
0
 
LVL 30

Expert Comment

by:SiddharthRout
ID: 34911883
If you still want a loop then try this...

Sub pastey()
    Dim strPM1
    Dim ws As Worksheet, Wks As Worksheet
    
    '~~> Replace ????? with the relevant sheetname
    'strPM1 = Sheets("????").Range("PreviousMonth1")
    
    For Each ws In ThisWorkbook.Sheets
        If ws.Name = "C'YearTrendP&L-IRE(24)" Then
            Set Wks = Sheets("C'YearTrendP&L-IRE(24)")
        ElseIf ws.Name = "C'tYearTrendP&L-UK(25)" Then
            Set Wks = Sheets("C'tYearTrendP&L-UK(25)")
        End If
        
        If Not Wks Is Nothing Then
            With Wks.Columns(strPM1 & ":" & strPM1)
                .Copy
                .PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
                :=False, Transpose:=False
            End With
        End If
    Next
    
    MsgBox "Finished Copying and Pasting"
End Sub

Open in new window


Sid
0
 

Assisted Solution

by:Melakh
Melakh earned 167 total points
ID: 34911893
Sub pastey()
'
   Dim arrSheetNames as Variant
   Dim strPM1
   Dim i as integer

   arrSheetNames = ("C'YearTrendP&L-IRE(24)", "C'tYearTrendP&L-UK(25)")
   strPM1 = Range("PreviousMonth1")

   For i = LBound(arrSheetNames) to UBound(arrSheetNames)
      Sheets(arrSheetNames(i)).Select
       Columns(strPM1 & ":" & strPM1).Select
       Selection.Copy
       Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
           :=False, Transpose:=False
   Next i

   Sheets("IRETB(23) ").Select
   MsgBox "Finished Copying and Pasting"

End Sub

Open in new window


There are better ways to do the copy and paste, you don't need to hop between sheets in VBA, but this is a simple edit to your code so you should be able to maintain it.
0
Master Your Team's Linux and Cloud Stack!

The average business loses $13.5M per year to ineffective training (per 1,000 employees). Keep ahead of the competition and combine in-person quality with online cost and flexibility by training with Linux Academy.

 

Author Comment

by:Patrick O'Dea
ID: 34911895
Thanks siddharthrout,

I may need to run this procedure for up to 10 or 11 sheets.

Would a loop be neater in this case??
0
 
LVL 30

Expert Comment

by:SiddharthRout
ID: 34911901
I have already replied. See my 2nd post above ;)

Sid
0
 
LVL 30

Expert Comment

by:SiddharthRout
ID: 34911905
If it is for all sheets then the code that I gave can be further trimmed :)

Sid
0
 
LVL 30

Expert Comment

by:SiddharthRout
ID: 34911913
Please follow this code in case you want to perform the copy past in all the sheets.

Sub pastey()
    Dim strPM1
    Dim ws As Worksheet, Wks As Worksheet
    
    '~~> Replace ????? with the relevant sheetname
    'strPM1 = Sheets("????").Range("PreviousMonth1")
    
    For Each ws In ThisWorkbook.Sheets
        Set Wks = Sheets(ws.Name)
        
        With Wks.Columns(strPM1 & ":" & strPM1)
            .Copy
            .PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
            :=False, Transpose:=False
        End With
    Next
    
    MsgBox "Finished Copying and Pasting"
End Sub

Open in new window


Sid
0
 

Author Comment

by:Patrick O'Dea
ID: 34912108
Thanks sid,

It is NOT for all sheets so your first solution works fine.

Can you advise what the line below means?  I would not like to use the code without understanding it.
See the following line.  Thanks.

 If Not Wks Is Nothing Then
0
 
LVL 30

Expert Comment

by:SiddharthRout
ID: 34912215
Sure :)

I have declared Wks as a worksheet. So when I am looping through the worksheet, when I find a match, I am storing that in Wks. I don't want the code copy paste to run each time the for 'loops' as it will give me an error as Wks would be empty. To stop that I used the line

If Not Wks Is Nothing Then

Sid
0
 
LVL 41

Assisted Solution

by:dlmille
dlmille earned 166 total points
ID: 34913304
You were very close...

Sub pastey()
Dim sh As Variant, mySheets() As String
Dim strPM1
   
    mySheets() = Split("C'YearTrendP&L-IRE(24);C'tYearTrendP&L-UK(25)", ";")

    For Each sh In mySheets
        Columns(strPM1 & ":" & strPM1).Select
        Selection.Copy
        Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
            :=False, Transpose:=False
    Next sh
   
    Sheets("IRETB(23) ").Select
    MsgBox "Finished Copying and Pasting"
End Sub
0
 

Author Closing Comment

by:Patrick O'Dea
ID: 34914182
Thanks all,

Working well now.
0

Featured Post

Are your AD admin tools letting you down?

Managing Active Directory can get complicated.  Often, the native tools for managing AD are just not up to the task.  The largest Active Directory installations in the world have relied on one tool to manage their day-to-day administration tasks: Hyena. Start your trial today.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

This article will guide you to convert a grid from a picture into Excel format using Microsoft OneNote and no other 3rd party application.
When you see single cell contains number and text, and you have to get any date out of it seems like cracking our heads.
The viewer will learn how to create a normally distributed random variable in Excel, use a normal distribution to simulate the return on an investment over a period of years, Create a Monte Carlo simulation using a normal random variable, and calcul…
This Micro Tutorial demonstrate the bugs in Microsoft Excel for Mac with Pivot Charts.

831 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question