VBA 如果单元格等于“”做“”,否则转到下一张

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17483098/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-08 16:03:03  来源:igfitidea点击:

VBA If cell equals "" do "", else go to next sheet

excelvbaexcel-vba

提问by atomoutside

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

我希望 VBA 代码执行此操作:如果单元格等于“blah blah”,则插入新列,否则移至下一张纸。事情是,如果我没有运行它

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!

然后一切正常(除了转到下一张纸)。当我添加 wSheet 时,即使单元格不等于 2013 06,代码仍保留在第一个活动工作表中创建额外的列。有什么建议吗?谢谢!

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

回答by

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 .Selectmethod so I have optimized your code a bit. See if this works as intended:

你真的不需要声明else,只是 - 什么都不做,这意味着让循环进入下一张纸。也不建议使用该.Select方法,因此我对您的代码进行了一些优化。看看这是否按预期工作:

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