下面的代码要求用户选择文件,然后代码“对所有选定文件进行处理”。代码的消息框部分(仅用于调试目的)正确显示了每个选定的文件,但是代码的“添加工作表”部分试图将工作表仅添加到每个选定的工作簿中的一个循环的迭代(因此,如果用户选择4个文件,它将尝试将“测试”表添加到其中一个文件4次)。
Dim myFile As Variant
Dim wi As Integer
Dim wb As Workbook
Dim fOpen As Boolean
myFile = Application.GetOpenFilename(MultiSelect:=True)
If Not IsArray(myFile) Then
Exit Sub
Else
For wi = LBound(myFile) To UBound(myFile)
'If workbook already open, activate. otherwise open it
On Error Resume Next
Set wb = Workbooks(Dir(myFile(wi)))
fOpen = Not (wb Is Nothing)
On Error GoTo 0 ' or point to error handler
If Not fOpen Then
Set wb = Workbooks.Open(myFile(wi)) 'if file is not open, open it
End If
wb.Activate
MsgBox myFile(wi)
wb.Sheets.Add.Name = "TEST"
next wi