添加错误处理以在执行前检查条件

时间:2019-03-20 05:41:46

标签: excel

您好,而且比您所有的时间都多,下面是我的代码,电子表格上有一个RUN按钮,它执行SUB RUN ALL宏。第一个调用函数删除所有选项卡,并从我的桌面上名为“ MyFiles”的文件中导入工作表。

我想要做的是先检查该文件的存在,然后再执行其他操作,如果不存在,则显示一条短消息并退出子菜单,而不执行其他任何操作。

我应该在IMPORT DATA子目录中添加一些内容吗?还是让一个新的子程序首先运行并检查该文件,如果不存在则退出?

谢谢大家。

Sub Run_All()

Call Import_Data
Call Cut_Series2
Call Cut_Series5
Call Cut_Series6
Call Cut_Series8
Call Cut_SeriesH
Call Cut_Trailers
Call Cut_PPE
Call Cut_Dewatering
Call Cut_Nicolas
Call Cut_Facilities

End Sub



Sub Import_Data()

Dim x As Workbook
Dim targetWorkbook As Workbook
Dim xWs As Worksheet

Application.ScreenUpdating = False
Application.DisplayAlerts = False

' This part delets all sheets except the summary tab
     For Each xWs In Application.ActiveWorkbook.Worksheets
        If xWs.Name <> "Summary" Then
            xWs.Delete
        End If
    Next

' This part will get the raw data from the downloaded file on the desktop
     Set x = Workbooks.Open("C:\Users\mohammad.reza\Desktop\MyFiles.xls")
     Set targetWorkbook = Application.ActiveWorkbook

' This part will copy the sheet into this workbook
     With x.Sheets("MyFiles").UsedRange
     ThisWorkbook.Sheets.Add(After:=Sheets(Sheets.Count)).Range("A1").Resize( _
        .Rows.Count, .Columns.Count) = .Value
     End With
     x.Close

' This part will rename the sheet and move it to the end
ActiveSheet.Name = "RAW DATA"
ActiveSheet.Move After:=Worksheets(Worksheets.Count)

Application.DisplayAlerts = True
Application.ScreenUpdating = True


End Sub

1 个答案:

答案 0 :(得分:1)

如果将<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script> <div id="app" />设置为函数,那么如果找不到文件,则可以返回成功/失败并退出man sub。

Import_Data