使用VBA解析多个Excel工作簿

时间:2017-07-15 05:22:15

标签: excel vba excel-vba

我不擅长VBA(我的典型用例是录制宏,清理和修改VBA而不是从头开始创建任何东西)。在尝试使用Kutools整合它们之前,我试图减少约300个excel工作簿。

我想出了一些vba来剥离这些工作簿的一些不必要的部分,以实现我的整合。在单独在任何工作簿上运行时,此代码可以正常运行:

Sub PrepWorkbook()
    Dim Sh As Worksheet
    For Each Sh In ThisWorkbook.Worksheets
        If Sh.Visible = True Then
            Sh.Activate
            Sh.Cells.Copy
            Sh.Range("A1").PasteSpecial Paste:=xlValues
            Sh.Range("A1").Select
        End If
    Next Sh
    Application.CutCopyMode = False
        Dim ws As Worksheet

    For Each ws In Worksheets
        ws.Cells.Validation.Delete
    Next ws
    Application.DisplayAlerts=FALSE
    Sheets("Instructions").Delete
    Sheets("Dropdowns").Delete
    Sheets("Dropdowns2").Delete
    Sheets("Range Reference").Delete
    Sheets("All Fields").Delete
    Sheets("ExistingData").Delete
    Application.DisplayAlerts=TRUE
End Sub

我在stackoverflow上发现了一些优秀的代码,它在多个工作簿中运行预定的任务,我试图根据我的目的进行调整:

Sub ProcessFiles()
    Dim Filename, Pathname As String
    Dim wb As Workbook

    Pathname = ActiveWorkbook.Path & "\Files\"
    Filename = Dir(Pathname & "*.xls")
    Do While Filename <> ""
       Set wb = Workbooks.Open(Pathname & Filename)
        DoWork wb
        wb.Close SaveChanges:=True
        Filename = Dir()
    Loop
End Sub


Sub DoWork(wb As Workbook)
    With wb
        'Do your work here
        .Worksheets(1).Range("A1").Value = "Hello World!"
    End With
End Sub

原创主题可以在这里找到: Run same excel macro on multiple excel files

我已经尝试将我的代码插入到&#34;&#39;在这里工作&#34;和#34; .Worksheets(1).Range(&#34; A1&#34;)。值=&#34; Hello World!&#34;&#34;原始vba中的行,但没有成功。我也尝试过类似地将我的解析代码插入到其他一些解决方案中,以便跨多个excel工作簿执行宏而没有成功。

它所调用的工作簿正在打开并保存,但我的代码试图完成的实际工作并没有发生(没有记录错误)。我怀疑我插入的一段代码是不相容的,这种方式对于比我更了解的人来说非常明显。

有人可以在这里提供一些帮助/指导吗?我真的只需要关于如何执行原始&#34; PrepWorkbook&#34;的代码或方向。在&#34; C:\ Temp \ Workbooks&#34;

中找到的300个工作簿上的VBA

2 个答案:

答案 0 :(得分:0)

在您的第一部分代码中,您必须对齐变量而不使用THISWORKBOOK,因为这会使它与运行的位置隔离开来。在评论中使用'PG下方的行。我也不认为你的第二个宏需要'WITH WB代码。你的第一个在你的床单上循环。

为了清晰起见,更改了宏的名称

Sub DoWork(wb As Workbook)
Dim Sh As Worksheet
For Each Sh In wb.Sheets'PG adjustments
    If Sh.Visible = True Then
        Sh.Activate
        Sh.Cells.Copy
        Sh.Range("A1").PasteSpecial Paste:=xlValues
        Sh.Range("A1").Select
    End If
Next Sh'PG adjustments
Application.CutCopyMode = False
    Dim ws As Worksheet

For Each ws In wb.Sheets 'PG seems redundant to above, but harmless.
    ws.Cells.Validation.Delete
Next ws
Application.DisplayAlerts=FALSE
Sheets("Instructions").Delete
Sheets("Dropdowns").Delete
Sheets("Dropdowns2").Delete
Sheets("Range Reference").Delete
Sheets("All Fields").Delete
Sheets("ExistingData").Delete
Application.DisplayAlerts=TRUE
End Sub

答案 1 :(得分:0)

考虑一下。

Sub Example()
    Dim MyPath As String, FilesInPath As String
    Dim MyFiles() As String, Fnum As Long
    Dim mybook As Workbook
    Dim CalcMode As Long
    Dim sh As Worksheet
    Dim ErrorYes As Boolean

    'Fill in the path\folder where the files are
    MyPath = "C:\Users\Ron\test"

    'Add a slash at the end if the user forget it
    If Right(MyPath, 1) <> "\" Then
        MyPath = MyPath & "\"
    End If

    'If there are no Excel files in the folder exit the sub
    FilesInPath = Dir(MyPath & "*.xl*")
    If FilesInPath = "" Then
        MsgBox "No files found"
        Exit Sub
    End If

    'Fill the array(myFiles)with the list of Excel files in the folder
    Fnum = 0
    Do While FilesInPath <> ""
        Fnum = Fnum + 1
        ReDim Preserve MyFiles(1 To Fnum)
        MyFiles(Fnum) = FilesInPath
        FilesInPath = Dir()
    Loop

    'Change ScreenUpdating, Calculation and EnableEvents
    With Application
        CalcMode = .Calculation
        .Calculation = xlCalculationManual
        .ScreenUpdating = False
        .EnableEvents = False
    End With

    'Loop through all files in the array(myFiles)
    If Fnum > 0 Then
        For Fnum = LBound(MyFiles) To UBound(MyFiles)
            Set mybook = Nothing
            On Error Resume Next
            Set mybook = Workbooks.Open(MyPath & MyFiles(Fnum))
            On Error GoTo 0

            If Not mybook Is Nothing Then


                'Change cell value(s) in one worksheet in mybook
                On Error Resume Next
                With mybook.Worksheets(1)
                    If .ProtectContents = False Then
                        .Range("A1").Value = "My New Header"
                    Else
                        ErrorYes = True
                    End If
                End With


                If Err.Number > 0 Then
                    ErrorYes = True
                    Err.Clear
                    'Close mybook without saving
                    mybook.Close savechanges:=False
                Else
                    'Save and close mybook
                    mybook.Close savechanges:=True
                End If
                On Error GoTo 0
            Else
                'Not possible to open the workbook
                ErrorYes = True
            End If

        Next Fnum
    End If

    If ErrorYes = True Then
        MsgBox "There are problems in one or more files, possible problem:" _
             & vbNewLine & "protected workbook/sheet or a sheet/range that not exist"
    End If

    'Restore ScreenUpdating, Calculation and EnableEvents
    With Application
        .ScreenUpdating = True
        .EnableEvents = True
        .Calculation = CalcMode
    End With
End Sub

来源:https://www.rondebruin.nl/win/s3/win010.htm