Still celebrating National IT Professionals Day with 3 months of free Premium Membership. Use Code ITDAY17

x
?
Solved

Simple VBA Loop

Posted on 2011-02-16
11
Medium Priority
?
215 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
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
11 Comments
 
LVL 30

Accepted Solution

by:
SiddharthRout earned 668 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 668 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
Industry Leaders: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

 

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 42

Assisted Solution

by:dlmille
dlmille earned 664 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

New feature and membership benefit!

New feature! Upgrade and increase expert visibility of your issues with Priority Questions.

Question has a verified solution.

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

Introduction This Article briefly covers methods of calculating the NPV and IRR variants in Excel as well as the limitations in calculating and interpreting IRR results. Paraphrasing Richard Shockley, author of my favourite finance reference tex…
How to get Spreadsheet Compare 2016 working with the 64 bit version of Office 2016
The viewer will learn how to use the =DISCRINV command to create a discrete random variable, use this command to model a set of probabilities and outcomes in a Monte Carlo simulation, and learn how to find the standard deviation of a set of probabil…
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…

688 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