简体   繁体   English

使用VBA解析多个Excel工作簿

[英]Parsing Multiple Excel Workbooks with VBA

I am not super good at VBA (my typical use cases are recording Macros, and cleaning and modifying VBA as opposed to creating anything from scratch). 我不太擅长VBA(我的典型用例是录制宏,并清理和修改VBA,而不是从头开始创建任何东西)。 I'm trying to slim down ~300 excel workbooks before consolidating them all using Kutools. 我试图在使用Kutools合并它们之前精简〜300个excel工作簿。

I came up with a bit of vba to strip some unnecessary parts of these workbooks to enable my consolidation. 我想出了一些vba来剥离这些工作簿中不必要的部分,以实现合并。 This code works without issue when run on any of the workbooks individually: 单独在任何工作簿上运行时,此代码都可以正常工作:

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

I found an excellent bit of code on stackoverflow that runs a predetermined task across multiple workbooks that I am tried adapting for my purposes: 我在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

Original thread can be found here: Run same excel macro on multiple excel files 原始线程可以在这里找到: 在多个Excel文件上运行相同的Excel宏

I've tried inserting my code into the the "'Do your work here" and ".Worksheets(1).Range("A1").Value = "Hello World!"" lines in the original vba, but have had no success. 我尝试将我的代码插入原始vba中的“在这里做你的工作”和“ .Worksheets(1).Range(“ A1”)。Value =“ Hello World!”“行中,但没有成功。 I've also tried similarly inserting my parsing code into a few other solutions to executing macros across multiple excel workbooks with no success. 我还尝试过类似地将解析代码插入其他一些解决方案中,从而在多个excel工作簿中执行宏都没有成功。

The workbooks it calls upon are being opened and saved, but the actual work my code is trying to accomplish isn't happening (without logging an error). 它所调用的工作簿正在打开并保存,但是我的代码试图完成的实际工作并未发生(没有记录错误)。 I suspect that a piece of the code I'm inserting is incompatible in a way that would be very obvious to someone more knowledgable than I am. 我怀疑我要插入的一段代码在某种程度上是不兼容的,这种方式对于比我更懂行的人来说非常明显。

Can anyone offer some help/guidance here? 有人可以在这里提供一些帮助/指导吗? I really just need code or direction on how to execute my original "PrepWorkbook" VBA on the 300 workbooks found in "C:\\Temp\\Workbooks" 我真的只需要有关如何在“ C:\\ Temp \\ Workbooks”中找到的300个工作簿上执行原始的“ PrepWorkbook” VBA的代码或指导。

In your first section of code, you have to align the variables and not use THISWORKBOOK, as that keeps it isolated to where it's run from. 在代码的第一部分中,您必须对齐变量而不使用THISWORKBOOK,因为这会将其与运行的地方隔离开来。 Use below the line with 'PG in comments. 在注释的'PG'行下方使用。 I also don't think you'll need the 'WITH WB code in your second macro. 我也不认为您不需要第二个宏中的“ WITH WB代码”。 Your first one loops through your sheets. 您的第一个循环浏览工作表。

Changed the name of macro for clarity 为了清楚起见,更改了宏的名称

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

Consider this. 考虑一下。

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

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM