Solved

Simple VBA Loop

Posted on 2011-02-16
11
177 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
 

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
How to run any project with ease

Manage projects of all sizes how you want. Great for personal to-do lists, project milestones, team priorities and launch plans.
- Combine task lists, docs, spreadsheets, and chat in one
- View and edit from mobile/offline
- Cut down on emails

 
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

How to run any project with ease

Manage projects of all sizes how you want. Great for personal to-do lists, project milestones, team priorities and launch plans.
- Combine task lists, docs, spreadsheets, and chat in one
- View and edit from mobile/offline
- Cut down on emails

Join & Write a Comment

Suggested Solutions

Introduction This Article is a follow-up to my Mappit! Addin Article (http://www.experts-exchange.com/A_2613.html), it was inspired by an email posting I made to EUSPRIG (http://www.eusprig.org/index.htm), I will briefly cover: 1) An overvie…
This article descibes how to create a connection between Excel and SAP and how to move data from Excel to SAP or the other way around.
The viewer will learn how to use a discrete random variable to simulate the return on an investment over a period of years, create a Monte Carlo simulation using the discrete random variable, and create a graph to represent the possible returns over…
This Micro Tutorial will demonstrate in Google Sheets how to use the HYPERLINK function to create live links inside your spreadsheet.

762 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

Need Help in Real-Time?

Connect with top rated Experts

21 Experts available now in Live!

Get 1:1 Help Now