2016-01-21 26 views
0

我有宏下面運行工作簿中的所有工作表,它運行通過特定目錄中的所有文件。但不幸的是,它僅適用於每個工作簿中的最後一張工作表。它應該適用於每張紙。有人可以糾正我的代碼嗎?Excel VBA只在最後一張工作表

Sub LoopThroughFiles() 
    Application.ScreenUpdating = False 
    FolderName = "C:\Users\Karolek\Desktop\E\3\" 
    If Right(FolderName, 1) <> Application.PathSeparator Then FolderName = FolderName & Application.PathSeparator 
    Fname = Dir(FolderName & "*.xls") 

    'loop through the files 
    Do While Len(Fname) 

     With Workbooks.Open(FolderName & Fname) 

      ' here comes the code for the operations on every file the code finds 

      Call LoopThroughSheets 

     End With 

     ' go to the next file in the folder 
     Fname = Dir 

    Loop 

End Sub 

Sub LoopThroughSheets() 

    Dim ws As Worksheet 
    For Each ws In ActiveWorkbook.Worksheets 

    Call naprawa 

    Next ws 
    ActiveWorkbook.Close savechanges:=True 
End Sub 



Sub naprawa() 

    Dim fndList As Variant 
    Dim rplcList As Variant 
    Dim x As Long 

    fndList = Array("Louver-", "Lvrs ", "gauge ", "Galvanized ", "Pieces") 
    rplcList = Array("Lvr-", "Louvers ", "ga ", "Glvnzd ", "Pcs") 
    For x = LBound(fndList) To UBound(fndList) 
    Range("C:C,D:D").Select 
    Selection.Replace What:=fndList(x), Replacement:=rplcList(x), LookAt:=xlPart, _ 
    SearchOrder:=xlByRows, MatchCase:=False, SearchFormat:=False, _ 
    ReplaceFormat:=False 

    Next x 

End Sub 

回答

1

爲什麼這需要在三個獨立的潛艇?這可以在一個子文件中完成:

Sub LoopThroughFiles() 

    Dim ws As Worksheet 
    Dim lCalc As XlCalculation 
    Dim sFldrPath As String 
    Dim sFileName As String 
    Dim aFindList() As String 
    Dim aRplcList() As String 
    Dim i As Long 

    sFldrPath = "C:\Test\" 
    If Right(sFldrPath, 1) <> Application.PathSeparator Then sFldrPath = sFldrPath & Application.PathSeparator 
    sFileName = Dir(sFldrPath & "*.xls*") 

    aFindList = Split("Louver-,Lvrs ,gauge ,Galvanized ,Pieces", ",") 
    aRplcList = Split("Lvr-,Louvers ,ga ,Glvnzd ,Pcs", ",") 

    With Application 
     lCalc = .Calculation 
     .Calculation = xlCalculationManual 
     .EnableEvents = False 
     .ScreenUpdating = False 
    End With 

    On Error GoTo CleanExit 

    'loop through the files 
    Do While Len(sFileName) > 0 
     With Workbooks.Open(sFldrPath & sFileName) 
      For Each ws In .Sheets 
       For i = LBound(aFindList) To UBound(aFindList) 
        ws.Range("C:D").Replace aFindList(i), aRplcList(i), xlPart 
       Next i 
      Next ws 
      .Close True 
     End With 

     ' go to the next file in the folder 
     sFileName = Dir 
    Loop 

CleanExit: 
    With Application 
     .Calculation = lCalc 
     .EnableEvents = True 
     .ScreenUpdating = True 
    End With 

End Sub 
+0

錯誤13:行:lCalc =。計算值:類型不匹配 –

+0

刪除該行然後再試一次。雖然我很驚訝,你會得到一個錯誤的線。您還需要將'.Calculation = lCalc'中最後一行的一行更改爲'.Calculation = xlCalculationAutomatic' – tigeravatar

+0

而且我知道代碼有效,因爲我使用模擬數據創建了示例工作簿,其中包括要更改的單詞,並且代碼成功運行並更改了指定文件夾路徑中所有工作簿中所有工作表中的所有實例。 – tigeravatar

相關問題