如何调试这个Excel麻烦?

时间:2017-07-04 09:07:10

标签: excel vba excel-vba

Sub Macro3()
'
' Macro3 Macro
'

'
    Dim MyFile As String
MyFile = Application.GetOpenFilename(MultiSelect:=True)
Workbooks.Open (MyFile)
    Range("A2").Select
    Range(Selection, Selection.End(xlDown)).Select
    Application.DisplayAlerts = False
    Selection.Copy
    ActiveWorkbook.Close
    Application.DisplayAlerts = True
    Windows("Jane macro test.xlsx").Activate
    Sheets("Sheet2").Select
    Range("B2").Select
lMaxRows = Cells(Rows.Count, "B").End(xlUp).Row
Range("B" & lMaxRows + 1).Select
 ActiveSheet.Paste



End Sub

它一直说我的代码有运行时错误13和不匹配。谁知道如何解决?如果我将MultiSelect更改为False,我可以使用它,但我需要它在多个文件夹上运行。我该怎么做呢?

1 个答案:

答案 0 :(得分:0)

试试这样:

Option Explicit

Sub Macro3()

    Dim MyFile      As Variant
    Dim counter     As Long
    Dim wb          As Workbook

    MyFile = Application.GetOpenFilename(MultiSelect:=True)

    For counter = LBound(MyFile) To UBound(MyFile)            
        Set wb = Workbooks.Open(MyFile(counter))
        MsgBox wb.Name

'    Range("A2").Select
'    Range(Selection, Selection.End(xlDown)).Select
'    Application.DisplayAlerts = False
'    Selection.Copy
'    ActiveWorkbook.Close
'    Application.DisplayAlerts = True
'
'    Windows("Jane macro test.xlsx").Activate
'    Sheets("Sheet2").Select
'    Range("B2").Select
'    lMaxRows = Cells(Rows.Count, "B").End(xlUp).Row
'    Range("B" & lMaxRows + 1).Select
'    ActiveSheet.Paste

    Next counter


End Sub

它遍历每个工作簿,然后在MsgBox中显示其名称。因此,您可以通过访问wb对象在循环中对其执行某些操作。 通常,请确保在顶部声明Option Explicit,以便编译器检查每个变量是否存在并避免运行时出错。