【问题标题】:How do I run the same macro on multiple Excel files?如何在多个 Excel 文件上运行相同的宏?
【发布时间】:2020-01-25 00:41:40
【问题描述】:

此宏将逗号分隔的值放入不同的单元格,当我在一个 Excel 文件中使用它时它可以正常工作:

Sub toColumns()
'
' toColumns Macro
' Changes csv to columns
'
' Keyboard Shortcut: Ctrl+a
'
    Columns("A:A").Select
    Selection.TextToColumns Destination:=Range("A1"), DataType:=xlDelimited, _
        TextQualifier:=xlDoubleQuote, ConsecutiveDelimiter:=False, Tab:=True, _
        Semicolon:=False, Comma:=True, Space:=False, Other:=False, FieldInfo _
        :=Array(Array(1, 1), Array(2, 1), Array(3, 1), Array(4, 1), Array(5, 1), Array(6, 1), _
        Array(7, 1), Array(8, 1)), TrailingMinusNumbers:=True
End Sub

我正在尝试this 为文件夹中的所有文件执行此操作。所以改编的代码是:

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

    Pathname = "H:\Macro\positions"
    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
        Columns("A:A").Select
        Selection.TextToColumns Destination:=Range("A1"), DataType:=xlDelimited, _
            TextQualifier:=xlDoubleQuote, ConsecutiveDelimiter:=False, Tab:=True, _
            Semicolon:=False, Comma:=True, Space:=False, Other:=False, FieldInfo _
            :=Array(Array(1, 1), Array(2, 1), Array(3, 1), Array(4, 1), Array(5, 1), Array(6, 1), _
            Array(7, 1), Array(8, 1)), TrailingMinusNumbers:=True
    End With
End Sub

但是当我运行它时没有任何反应。 这是我第一次使用 VBA 和 Excel 宏。

我错过了什么?

【问题讨论】:

标签: excel vba csv


【解决方案1】:

三件事

  1. Pathname = "H:\Macro\positions" 更改为Pathname = "H:\Macro\positions\"
  2. wb.Close SaveChanges:=True 行之后添加Doevents,以便excel 有时间保存文件,否则excel 可能会崩溃。
  3. DoWork(wb As Workbook) 更改为此。您必须完全限定您的对象,否则它可能会使用错误的工作表。

代码

Sub DoWork(wb As Workbook)
    With wb.Sheets(1) '<~~ Or change this to the relevant sheet number
        .Columns(1).TextToColumns Destination:=.Range("A1"), DataType:=xlDelimited, _
        TextQualifier:=xlDoubleQuote, ConsecutiveDelimiter:=False, Tab:=True, _
        Semicolon:=False, Comma:=True, Space:=False, Other:=False, FieldInfo _
        :=Array(Array(1, 1), Array(2, 1), Array(3, 1), Array(4, 1), Array(5, 1), Array(6, 1), _
        Array(7, 1), Array(8, 1)), TrailingMinusNumbers:=True
    End With
End Sub

【讨论】:

  • 感谢您的帮助,但是,即使使用这三个步骤,当我单击运行时它也是瞬时的,并且没有任何反应。我预计几分钟可以处理超过 10000 个文件。
  • 您确定是.xls 而不是.xlsx.xlsm 文件吗?
  • 如果是.xls/.xlsx/.xlsm的混合,则将行改为Dir(Pathname &amp; "*.xls*")
  • 如上图你使用我的Sub DoWork(wb As Workbook)了吗?
【解决方案2】:

如果我理解正确,您想修改 10,000 个 excel 文件。那正确吗?试试这个方法。

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
                ' PUT YOUR CODE RIGHT HERE . . .


                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

【讨论】:

    猜你喜欢
    • 2013-01-23
    • 2017-05-30
    • 2015-06-21
    • 1970-01-01
    • 2023-03-10
    • 1970-01-01
    • 2014-12-09
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多