Go Premium for a chance to win a PS4. Enter to Win

x
?
Solved

Simple VBA Loop

Posted on 2011-02-16
11
Medium Priority
?
219 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 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
What does it mean to be "Always On"?

Is your cloud always on? With an Always On cloud you won't have to worry about downtime for maintenance or software application code updates, ensuring that your bottom line isn't affected.

 

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

Vote for the Most Valuable Expert

It’s time to recognize experts that go above and beyond with helpful solutions and engagement on site. Choose from the top experts in the Hall of Fame or on the right rail of your favorite topic page. Look for the blue “Nominate” button on their profile to vote.

Question has a verified solution.

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

In Part II of this series, I will discuss how to identify all open instances of Excel and enumerate the workbooks, spreadsheets, and named ranges within each of those instances.
Windows Explorer lets you open cabinet (cab) files like any other folder. In VBA you can easily handle normal files and folders, but opening and indeed creating cabinet files takes a lot more - and that's you'll find here.
The viewer will learn how to create two correlated normally distributed random variables in Excel, use a normal distribution to simulate the return on different levels of investment in each of the two funds over a period of ten years, and, create a …
This Micro Tutorial will demonstrate how to use a scrolling table in Microsoft Excel using the INDEX function.

926 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