我使用 Excel 中的“记录宏”按钮创建基本宏。然后我进行相应的编辑以使宏执行我想要执行的操作。
在本例中,我手动打开 master.xlsx 文件。然后,我在 master.xlsx 中运行一个名为 week12 的宏。
此宏打开一个名为 Grant.xlsx 的文件,复制单元格 H16 的内容,然后将内容粘贴到 master.xlsx 单元格 N3 中。
我遇到的问题是,如果该文件不存在,我会收到一条消息,指出找不到该文件,然后收到运行时错误“1004”。
该宏的目的是打开 40 个不同的电子表格并复制单元格的内容并将其粘贴到 master.xlsx 中。 40 个文件中的任何一个或多个都可能丢失。下面的宏示例仅显示了 40 个中的 2 个宏。
Sub Week12()
'
' Week12 Macro
'
' Grant
'
If Err.Number > 0 Then
Err.Clear
End If
On Error GoTo 3
Sheets("SCORES").Select
Range("A1").Select
ChDir _
"K:\\\Grant"
Workbooks.Open Filename:= _
"K:\\\\Week 12.xlsx"
Range("H16").Select
Selection.Copy
Windows("Master.xlsb").Activate
Range("N3").Select
ActiveSheet.Paste
Range("A1").Select
Windows("Week 12.xlsx").Activate
ActiveWindow.Close
GoTo 4
3:
'if the file is missing put a O in N3
Range("N3").Select
ActiveCell.FormulaR1C1 = "O"
Range("A1").Select
If Err.Number > 0 Then
Err.Clear
End If
4:
' Adele
On Error GoTo 5
Sheets("SCORES").Select
Range("A1").Select
ChDir _
"K:\\\\Adele"
Workbooks.Open Filename:= _
"K:\\\\Adele\Week 12.xlsx"
Range("H16").Select
Selection.Copy
Windows("Master.xlsb").Activate
Range("N4").Select
ActiveSheet.Paste
Range("A1").Select
Windows("Week 12.xlsx").Activate
ActiveWindow.Close
GoTo 6
5:
'if the file is missing put a O in N4
Range("N4").Select
ActiveCell.FormulaR1C1 = "O"
Range("A1").Select
If Err.Number > 0 Then
Err.Clear
End If
6:
' Stuart Manvell
'and so on and so on for all 40 names
end sub
最佳答案
尝试以下方法,但您需要根据您的需求进行调整。
'Some Other Script here
'Ignore errors to allow for error evaluation
On Error Resume Next
ExcelFilePAth = "INSERT FILE PATH HERE"
'YAYAYA is just a random name
'Purpose is to generate an error if the File Path doesnt exisit
YAYAYA = GetAttr(ExcelFilePAth)
Select Case Err.Number
'If the File Path is valid the Error Number should be 0
'Else it will present an error message and then continue
Case Is = 0
'Insert your Script for processing the Excel Sheets Here
Case Else
'Insert what to do here
MsgBox "The File path below doesnt exisit:" & vbNewLine & _
vbNewLine & _
ExcelFilePAth
End Select
'Resume error checking
On Error GoTo 0
'Some Other Script here
关于excel - 宏错误处理,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34066981/