简体   繁体   中英

VBA If cell equals “” do “”, else go to next sheet

I want VBA code to do this: if cell equals "blah blah", then insert new columns, else move to next sheet. Thing is, that if I run it without

wSheet

then everything works (except for going to next sheet). When I add wSheet, code stays in the first active sheet creates additional columns, even though cell does not equal 2013 06. Any suggestions? Thanks!

Sub Macro2()
'
' Macro2 Macro
'
dim wSheet As Worksheet

For Each wSheet In Worksheets

If wSheet.Range("R1")="2013 06" Then
'If Range("R1") = "2013 06" Then
    Columns("R:T").Select
    Selection.Insert Shift:=xlToRight, CopyOrigin:=xlFormatFromLeftOrAbove
    Columns("L:N").Select
    Selection.Copy
    Columns("R:R").Select
    ActiveSheet.Paste
    Selection.Replace What:="2013 04", Replacement:="2013 06", LookAt:=xlPart _
        , SearchOrder:=xlByRows, MatchCase:=False, SearchFormat:=False, _
        ReplaceFormat:=False

ElseIf wSheet.Range("R1")<>"2013 06"  Then
'ElseIf Range("R1") <> "2013 06" Then
End If

Next wSheet

End Sub

You don't really need to state the else , just - do nothing, which means let the loop go to the next sheet. Its also not recommended to use the .Select method so I have optimized your code a bit. See if this works as intended:

Sub Macro2()
    Dim wSheet As Worksheet
    For Each wSheet In Worksheets
        If wSheet.Range("R1") = "2013 06" Then
            wSheet.Columns("R:T").Insert Shift:=xlToRight, CopyOrigin:=xlFormatFromLeftOrAbove
            wSheet.Columns("L:N").Copy
            wSheet.Paste
            wSheet.Columns("R:R").Replace What:="2013 04", Replacement:="2013 06", LookAt:=xlPart _
                , SearchOrder:=xlByRows, MatchCase:=False, SearchFormat:=False, _
                ReplaceFormat:=False
        End If
    Next wSheet
End Sub

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM