如何在Excel中添加多个语句如果(条件1)然后(closures窗口)和(End Sub)

我创build了一个macros复制特定的单元格并将其粘贴到新窗口(Excel)中。 我试图在粘贴数据之后在macros中添加一个If Then语句,如果一个特定的单元格是空白的(比方说A2),我希望macrosclosures该窗口并结束macros。 我已经尝试了下面的代码,但它给了我编译错误:块如果没有结束IF

Windows("Data.xlsx").Activate Rows("13:18").Select Selection.Copy Windows("Data Paste.xlsx").Activate Range("A1").Select ActiveSheet.Paste If ActiveSheet.Range("A2").Value = "" Then ActiveWindow.Close End Sub End If Range("A2:A6").SpecialCells(xlCellTypeBlanks).EntireRow.Delete End Sub 

为了更清楚,我需要的是; 第一行13:18从“DATA.xlsx”复制并粘贴到“Data Paste.xlsx”中,然后检查单元格A2是否为空,如果是,则closures“Data Paste.xlsx”窗口并停止macros运行。 如果A2单元格不是空的,我想要macros继续而不closures窗口,并继续下面的代码:

 Range("A2:A6").SpecialCells(xlCellTypeBlanks).EntireRow.Delete 'Rest of the code 

请find我的解决scheme。

您必须更正多个语法错误,如下面显示的示例Excel VBA Sub所示:

 Sub CopyClose() Windows("Data.xlsx").Activate Rows("13:18").Select Selection.Copy Windows("Data Paste.xlsx").Activate Range("A1").Select ActiveSheet.Paste ' check for the condition, and close the window and exit sub if true ' otherwise, execute the next line If ActiveSheet.Range("A2").Value = "" Then ActiveWindow.Close Else Range("A2:A6").SpecialCells(xlCellTypeBlanks).EntireRow.Delete End If End Sub 

希望这可能有帮助。

End Sub应该是Exit Sub。 退出提前终止,End表示代码的自然结束。

  If ActiveSheet.Range("A2").Value = "" Then ActiveWindow.Close Exit Sub End If 

我find了答案,而不是End Sub使用Exit Sub作品完美!

 Range("A1").Select ActiveSheet.Paste If ActiveSheet.Range("A2").Value = "" Then ActiveWindow.Close Exit Sub End If Range("A2:A6").SpecialCells(xlCellTypeBlanks).EntireRow.Delete End Sub