2017-07-04 70 views
1
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,我可以使用它,但我需要它在多個文件夾上運行。我該如何去做呢?如何調試這個Excel的麻煩?

+0

你知道如何「F8」,並通過代碼? – ja72

回答

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,以便您的編譯器將檢查每個變量是否存在並避免運行時發生錯誤。

+1

請記住,當您使用'MultiSelect:= True'時,'MyFile'將保存一個字符串數組' –

+0

@RikSportel - 謝謝,我修改了一下。 – Vityata