我创建一个宏来打开许多文件,并在最终文件中执行复制和粘贴等操作。 但我想在没有文件跳过与该文件相关的代码时
'create variables'
FinalFile = "order.xls"
Obj1 = "order-obj1.xls"
Obj1Range = "E11"
......
Windows(Obj1).Activate
Range(MyRange).Select
Selection.Copy
Windows(FinalFile).Activate
Range(Obj1Range).Select
ActiveSheet.Paste
Windows(Obj1).Activate
ActiveWindow.Close
Windows(Obj2).Activate
Range(MyRange).Select
Selection.Copy
Windows(FinalFile).Activate
Range(Obj2Range).Select
ActiveSheet.Paste
Windows(Obj2).Activate
ActiveWindow.Close
如果我无法打开某个文件,我收到运行时错误9.所以我的问题是如何跳过Obj1的代码并继续进入Obj2? 我希望你能理解我......
答案 0 :(得分:2)
使用commmand Dir()检查文件是否存在。
e.g。
If Dir(Obj1) <> "" Then
Windows(Obj1).Activate
Range(MyRange).Select
Selection.Copy
Windows(FinalFile).Activate
Range(Obj1Range).Select
ActiveSheet.Paste
Windows(Obj1).Activate
ActiveWindow.Close
End If
此外,您可能希望将此代码放入函数中以免重复,但这是另一个问题。
答案 1 :(得分:2)
<强> UNTESTED 强>
我将如何做到这一点。不使用.SELECT/.ACTIVATE
Dim destwb As Workbook
Sub Sample()
Dim FinalFile As String
Dim Obj1 As String, Obj2 As String
Dim MyRange As String, Obj1Range As String, Obj1Rang2 As String
Dim wb As Workbook
'~~> Change as applicable
FinalFile = "order.xls"
Obj1 = "order-obj1.xls"
Obj2 = "order-obj2.xls"
Obj1Range = "E11"
Obj2Range = "E12"
MyRange = "A1"
Set destwb = Workbooks(FinalFile)
On Error Resume Next
Set wb = Workbooks(Obj1)
On Error GoTo 0
If Not wb Is Nothing Then
CopyRange wb, MyRange, Obj1Range
DoEvents
Set wb = Nothing
End If
On Error Resume Next
Set wb = Workbooks(Obj2)
On Error GoTo 0
If Not wb Is Nothing Then
CopyRange wb, MyRange, Obj2Range
DoEvents
Set wb = Nothing
End If
End Sub
Sub CopyRange(w As Workbook, r1 As String, r2 As String)
On Error GoTo Whoa
Dim ws As Worksheet, rng As Range
Set ws = w.Sheets(1)
Set rng = ws.Range(r1)
r1.Copy destwb.Sheets("Sheet1").Range(r2)
DoEvents
wb.Close savechanges:=False
Exit Sub
Whoa:
MsgBox Err.Description
End Sub