VBA无法将数据从多个工作簿传输到主工作簿

时间:2016-10-01 10:10:11

标签: excel-vba pasting vba excel

我正在使用Excel 2013并尝试使用教程Transfer to Master from Multiple Workbooks中的以下代码将数据从多个工作簿传输到主工作簿。它将来自多个wkbks的数据添加到主wkbk中,每次粘贴在其上方数据下方的数据,而不是主数据中的单独电子表格。

我根据教程将代码放在MASTER工作簿中,但没有任何反应。我不太了解VBA。我刚刚学会了如何休息并运行代码,但这并没有真正告诉我任何事情,我不会想。

  1. 我的桌面上有一个名为' merge'使用一个名为MASTER的宏启用wkbk,其他3个非宏wkbk称为tblScheduleMergeTWO,tblScheduleMergeTHREE和tblScheduleMergeFOUR。
  2. 每个wkbk,包括MASTER,都有9列具有相同的字段标题,我不认为这个代码很重要。
  3. 我需要复制的3个wkbks对数据有不同的阴影,所以我可以告诉哪些数据来自哪个wkbk粘贴到MASTER上。
  4. 我尝试过的事:海报编辑 -

    1. 我打开MASTER wkbk并将光标放在wkbk中并从那里运行代码。

    2. 我已尝试使用其他一个需要从open复制的wkbks并尝试将其关闭,屏幕有时会闪烁一次,但在复制任何数据方面没有任何反应。

    3. 根据@Tony Dallimore建议,在Active.Workbook.Close之后和ActiveSheet.Paste Destination:之后移动Loop Application.DisplayAlerts = True并且它没有改变任何内容。我不确定它是否会删除任何东西以关闭wkbk,但他会更清楚。

    4. 根据#Tony Dallimore的建议,将Cells(erow, 9)更改为Cells(erow, lastcolumn),单独更改,并进行其他修改,但没有任何更改。

    5. 不明白#Tony Dallimore的第三个建议。是替换Range(Cells(2, 1), Cells(lastrow, lastcolumn)).Copy with SrcRange.Copy目的地:= DestTopLeftCell?我没有看到它会覆盖lastrow到lastcolumn。

    6. 我还尝试了另一个教程,但它不能从enter link description here起作用。没有发布代码以节省空间。

    7. 10/1/19 11:19 AM海报编辑 10.根据@Thomas Inzina的建议,我使用F8在他的代码中逐行排除故障发布。我立即注意到使用F8代码的起始行' With ThisWorkbook.Worksheets(" Sheet1")'在屏幕提示中显示为FileName =""当您单击ThisWorkbook或单击Sheet1时。它看起来甚至不能识别ThisWorkbook,它实际上被称为MASTER.xlsm。发生了什么?屏幕提示会显示文件名,但是,当您将光标悬停在“Do While FileName<>上时""&#39 ;.当我按F8然后,它会弹出一个消息说你的MASTER文件已经打开并且可能会损坏重新打开。当我选择NO时,我不希望它再次打开,我收到一个错误消息,询问我是否要结束或调试。如果我调试,那么' With Workbooks.Open(FolderPath& FileName)'被突出显示为问题。我只需要保存并关闭Master wkbk然后麻烦就消失了;然而,在' With Workbook.Open(FolderPath& FileName)'之后按F8跳过剩下的代码并返回到开头。在所有这些中,我都没有看到代码提供的屏幕提示显示它注意到我需要复制的wkbks。

      我很感激帮助。我也要查看这篇文章Other post to t/f data from multiple wkbks

      FileName = Dir可能错了吗?

      Sub copyDataFromMultipleWorkbooksIntoMaster()
      
      Dim FolderPath As String
      Dim FilePath As String
      Dim FileName As String
      'or Dim FolderPath As String, FilePath As String, FileName As String
      
      FolderPath = "C:\Users\PC-1\Desktop\Merge\"
      FilePath = FolderPath & "*.xls*"
      FileName = Dir(FilePath)
      
      'Don't know how many rows of data so define last row and column
      Dim lastrow As Long
      Dim lastcolumn As Long
      'will use in a loop as number columns and rows from which extract data
      
      Do While FileName <> ""
      Workbooks.Open (FolderPath & FileName)
      
      'Assign value to last row
      lastrow = ActiveSheet.Cells(Rows.Count, 1).End(xlUp).Row
      lastcolumn = ActiveSheet.Cells(1, Columns.Count).End(xlLeft).Column
      
      Range(Cells(2, 1), Cells(lastrow, lastcolumn)).Copy
      Application.DisplayAlerts = False
      'to disable alerts that you have a lot of data copied to clipboard, etc.
      Active.Workbook.Close
      
      'when go back to master to paste, we need to know which is next blank row to paste data
      erow = Sheet1.Cells(Rows.Count, 1).End(xlUp).Offset(1, 0)
      'Offset to go to next row
      ActiveSheet.Paste Destination:=Worksheets("Sheet1").Range(Cells(erow, 1), Cells(erow, 9))
      
      FileName = Dir
      
      Loop
      Application.DisplayAlerts = True
      
      
      
      End Sub
      

      2016年10月2日海报编辑 - 回应Tony Dallimore - 托尼,我仔细阅读了代码但认为我理解得足以运行它并看看会发生什么(然而,我会更深入地研究它并重新输入它);但是,当我试图运行它时没有任何反应。我是否应该将代码中的工作簿名称或任何工作表名称(例如WshtDestName)替换为代码?

      我收到运行时错误9下标超出范围错误,当我调试它时,突出显示了设置WshtDest = WbkDest.Worksheets(WshtDestName)。

      我以为我可能应该在我的MASTER.xlsm文件中用我的wksht的名称替换上面的WshtDestName。所以,我把&#34; Sheet1&#34;在括号中。 msg没有错误,但也没有发生任何事情。

      我想也许我要替换&#34; Data&#34;在2个常量Const WshtDestName As String = "Data"Const WshtSrcName As String = "Data"中,我的wksht的名字都在wkbks中,所以我把&#34; Sheet1&#34;在哪里&#34;数据&#34;曾经,而且,再一次,没有任何事情发生。

      我不知道开头的常数是否应该在Sub之后,所以我把它们移到Sub下的Dim之后,然后什么也没发生。

      当我点击F8查看每行代码时,屏幕提示就是这样:

      • 对于Application.ScreenUpdating = False,它说 Application.ScreenUpdating = True

      • 对于Set WbkDest = ThisWorkbook,屏幕提示为WbkSet = Nothing和ThisWorkbook =,但仅在黄色突出显示时说出这些内容。当按下F8并离开那条线时,当我把光标放在它上面时,它什么也没说。

      • 对于Set WshtDest = WbkDest.Worksheets(WshtDestName),屏幕提示为WshtDest = Nothing和WbkDest.Worksheets(WshtDestName)=下标超出范围,如果光标刚刚结束(WshtDestName),它说( &#34;数据&#34;),但只有在突出显示黄色时才会显示这些内容。当按下F8并离开那条线时,当我把光标放在它上面时,它什么也没说。

      • 除非我将(&#34;数据&#34;)更改为(&#34; Sheet1&#34;),否则我无法通过F8。我可以F8到FolderPath = WbkDest.Path&amp; &#34; \&#34; =&#34; C:\ Users | PC-1 \ Destktop \ Merge \&#34;在屏幕提示中,WbkDest.Path =&#34; C:\ Users | PC-1 \ Destktop \ Merge&#34;,这是正确的。

      • FilePath = FolderPath&amp; &#34; 的.xls &#34; =&#34; C:\ Users | PC-1 \ Destktop \ Merge \&#34; .xls *&#34;在如上所述的FolderPath正确的屏幕提示中,&#34; C:\ Users | PC-1 \ Destktop \ Merge \&#34;

      • FileName = Dir $(FilePath)=&#34; MASTER.xlsm&#34;在屏幕提示中,FilePath等于&#34; C:\ Users | PC-1 \ Destktop \ Merge * .xls *&#34;如上所述。

      • 设置RngDest = .Cells.Find(&#34; *&#34;,。Randge(&#34; A1&#34;),xlFormulas ,, xlByRows,xlPrevious)其中RngDest = Nothing in tip屏幕提示中没有任何内容弹出,xlFormulas为-4123,xlByRows为1,xlPrevious为2。

      • 如果RngDest什么都没有那么RngDest =提示中没有

      • HeaderCopied = False = HeaderCopied =提示中的False是不正确的b / c我的目的地wkbk,MASTER.xlsm在第1行中已经有一个标题行。

      • RowDestNext = 1 =屏幕提示中的RowDestNext = 1

      • 然后跳转到EndIf和EndWith

      • Do FileName&lt;&gt; &#34;&#34;和FileName&lt;&gt; WbkDest.Name,其中FileName和WbkDest.Name =&#34; MASTER.xlsm&#34;在屏幕提示中。

      • F8然后跳过其余代码到

        的末尾

        使用WshtDest     .Cells.EntireColumn.AutoFit   结束等等

      我也按照你输入的方式运行你的代码,除了我注释掉你说要注释的部分,如果我有标题,我取消注释你说取消注释的部分。它仍然没有用。

2 个答案:

答案 0 :(得分:1)

您可以直接直接复制到目的地范围,并避免完全使用剪贴板。

Sub copyDataFromMultipleWorkbooksIntoMaster()

    Dim FileName As String, FilePath As String, FolderPath As String
    Dim lastrow As Long, lastcolumn As Long
    Dim LastCell As Range

    With ThisWorkbook.Worksheets("Sheet1")
        Set LastCell = .Cells(.Rows.Count, 1)
    End With

    FolderPath = "C:\Users\PC-1\Desktop\Merge\"
    FilePath = FolderPath & "*.xls*"
    FileName = Dir(FilePath)

    Do While FileName <> ""
        With Workbooks.Open(FolderPath & FileName)

            'Assign value to last row
            lastrow = .Cells(.Rows.Count, 1).End(xlUp).Row
            lastcolumn = .Cells(1, .Columns.Count).End(xlLeft).Column

            .Range("A2", .Cells(lastrow, lastcolumn)).Copy LastCell.End(xlUp).Offset(1)

            .Close False

        End With
        FileName = Dir

    Loop

End Sub

答案 1 :(得分:1)

我已经设置了符合您描述的文件夹和工作簿。以下修订后的代码适合我。我希望原始代码全是你的。对于一些错误和不良做法,我可以很容易地原谅新手,但如果你按照你的建议从教程中得到这个,我会感到震惊。

我已添加评论以解释我的所有更改。如果有必要,请回来寻求更多解释,但是你为自己解密我的代码越多,你的技能发展得越快。我提供了注释来说明代码正在做什么,但很少有关于语句本身的评论。例如,Option Explicit一旦您知道它存在就很容易查找,因此无法解释其目的。

Option Explicit         ' Always have this statement at the top of every module

  ' Constants are fixed while a macro is running but can be changed
  ' if the data is redesigned. This defines the first data row of every
  ' worksheet is 2. That is, it allows for one header row. I could have used
  ' 2 within the code below. If you ever have to update code because the
  ' number of header rows has changed or a new column has been inserted in
  ' the middle of existing columns, you will understand why I use constants.
  Const RowDataFirst As Long = 2        ' Set to 1 if no header rows

  ' You assume that when you open a workbook, the active worksheet is the one
  ' required. This is only reliable if the workbooks only have one worksheet.
  ' I have defined one constant for the name of the worksheet within the
  ' destination workbook and one for name of the worksheet within every
  ' source workbook. I assume this is adequate. I will have alternative
  ' suggestions if it is not adequate.
  Const WshtDestName As String = "Data"
  Const WshtSrcName As String = "Data"
Sub copyDataFromMultipleWorkbooksIntoMaster()

  Dim FolderPath As String
  Dim FilePath As String
  Dim FileName As String
  Dim HeaderCopied As Boolean
  Dim RowDestNext As Long
  Dim RngDest As Range
  Dim RngSrc As Range
  Dim WbkDest As Workbook
  Dim WbkSrc As Workbook
  Dim WshtDest As Worksheet
  Dim WshtSrc As Worksheet

  Application.ScreenUpdating = False

  ' You need row numbers in both the source and the destination worksheets.
  ' Use names for variables that tell you exactly what the variable is for.
  ' While you are writing a macro, it is easy to remember odd names but if
  ' you return to the macro in six or twelve months will you still remember?
  ' I have a naming system which I always use. I can look at macros I wrote
  ' ten years ago and know what all the variable are which is an enormous help
  ' when updating old code. If you do not like my system then develop your own.
  ' My names consist of a series of keywords with the most global first.
  ' "Row" says the variable is a row number. "Wbk" says the variable is a
  ' workbook. "RowXxx" says the variable is a row number within worksheet or
  ' array Xxxx. "RowSrcXxx" says the variable is a row number for worksheet
  ' "Source". "Xxx" can be "First", "Crnt", "Next", Prev", "Last" or whatever
  ' I need for the current macro

  Dim RowSrcLast As Long

  ' My comment suggested you be consistent in your use of column numbers but
  ' comments do not allow enough room to explain. With some statements, having
  ' a different number of rows or columns in the source and destination can
  ' give funny results with truncation or duplication. If you know you only
  ' want 9 columns then use 9 in both source and destination ranges. If the
  ' number of columns might change then determine the number at runtime.
  Dim ColSrcLast As Long

  ' If you are handling multiple workbooks be explicit which workbook
  ' you are addressing.  This assumes the workbook into which the worksheets
  ' are collected is the workbook containing the macro.
  Set WbkDest = ThisWorkbook

  Set WshtDest = WbkDest.Worksheets(WshtDestName)
  ' Note a worksheet variable references the worksheet within its workbook.
  ' I do not need to write WbkDest.WshtDest.

  ' FolderPath = "C:\Users\PC-1\Desktop\Merge\"
  ' You can hard code the name of the folder into a macro but it is
  ' a bother when you move your workbooks. When all your workbooks
  ' are in the same folder, the following is more convenient
  FolderPath = WbkDest.Path & "\"

  FilePath = FolderPath & "*.xls*"

  ' Note Dir searches down the folder index for files that match the template.
  ' The sequence in which they are found depends on the sequence in which the
  ' files were added to the folder. There are other techniques if sequence is
  ' important.
  FileName = Dir$(FilePath)         ' Dir$ is marginally faster than Dir

  ' Your existing code adds new data to the end of the existing worksheet in
  ' Master.xlsm. This may be correct but it is more usual to clear the
  ' destination at the start of each run. Comment out the first block and uncomment
  ' the second block if you want to add to existing data.

  With WshtDest
    .Cells.EntireRow.Delete  ' Delete every row in worksheet
    HeaderCopied = False     ' There is no header within the destination worksheet
    RowDestNext = 1          ' First (only) header row will be copied from first
                             ' source worksheet to this row
  End With

  ' If you know that column A of the used rows of the active sheet contains no
  ' blank cells, the following is the easiest way of finding that last used row:
  '   RowDestLast = ActiveSheet.Cells(Rows.Count, 1).End(xlUp).Row
  ' But this technique is unreliable if there might be blank cells. No technique
  ' is 100% reliable but you would have very strange data if the technique I have
  ' used is not reliable for you.

  'With WshtDest
  '  ' Find last row with a value
  '  Set RngDest = .Cells.Find("*", .Range("A1"), xlFormulas, , xlByRows, xlPrevious)
  '  If RngDest Is Nothing Then
  '    ' No data has been found so the worksheet is empty
  '    HeaderCopied = False     ' There is no header within the destination worksheet
  '    RowDestNext = 1          ' First (only) header row will be copied from first
  '                             ' source worksheet to this row
  '  Else
  '    ' There is data within the worksheet. Assume the header row(s) are present.
  '    HeaderCopied = True
  '    RowDestNext = RngDest.Row + 1
  '  End If
  'End With

  ' Please indent your code within Do-Loops, If, etc. It makes your code
  ' much easier to read.

  ' All your workbooks are within the same folder. Master.xlsm will be one
  ' of those found but you do not want to use it as a source workbook.

  Do While FileName <> ""
    If FileName <> WbkDest.Name Then
      Set WbkSrc = Workbooks.Open(FolderPath & FileName)

      ' WbkSrc will be the active workbook but better to reference it explicitly

      With WbkSrc
        Set WshtSrc = .Worksheets(WshtSrcName)
      End With

      With WshtSrc
        ' Find last row with data if any
        Set RngSrc = .Cells.Find("*", .Range("A1"), xlFormulas, , xlByRows, xlPrevious)
        If RngSrc Is Nothing Then
          ' No data has been found so the worksheet is empty
        Else
          RowSrcLast = RngSrc.Row
          ' Find last column with data. Already know there is data
          RngSrc = .Cells.Find("*", .Range("A1"), xlFormulas, , xlByColumns, xlPrevious)
          ColSrcLast = RngSrc.Column

          If HeaderCopied Then
            ' Already have header row(s) in destination worksheet
            Set RngSrc = .Range(.Cells(RowDataFirst, 1), .Cells(RowSrcLast, ColSrcLast))
          Else
            ' Do not have header row(s) in destination worksheet. Include them in copy.
            Set RngSrc = .Range(.Cells(1, 1), .Cells(RowSrcLast, ColSrcLast))
            HeaderCopied = True
          End If
          RngSrc.Copy Destination:=WshtDest.Cells(RowDestNext, 1)  ' Copy data and formats
          RowDestNext = RowDestNext + RngSrc.Rows.Count            ' Step ready for next copy
        End If
      End With  ' WshtSrc

      WbkSrc.Close SaveChanges:=False
      Set WshtSrc = Nothing
      Set WbkSrc = Nothing

    End If  ' FileName <> WbkDest.Name

    FileName = Dir$

  Loop  ' While FileName <> "" And FileName <> WbkDest.Name

  With WshtDest
    .Cells.EntireColumn.AutoFit
  End With

  Application.ScreenUpdating = True

End Sub

回应OP对原始回答的评论的新部分

在我的原始答案中,我确实应该包含一些内容,但你也误入了我无法想象的领域。您还发现了我自己的测试遗漏的错误。

  

“我应该用我的工作簿名称替换任何东西......”

我应该说清楚。在Const WshtDestName As String = "Data"中,“数据”是我在其中累积数据的工作表的名称。我应该告诉你用你的工作表名称替换“数据”。

您的评论建议您更换:

 Set WshtDest = WbkDest.Worksheets(WshtDestName)

 Set WshtDest = WbkDest.Worksheets("Sheet1")

如果是,请更新Const声明。使用Const语句的目的是隔离可能与代码主体有关的内容。这使维护更容易。

避免使用默认名称“Sheet1”,“Sheet2”等。随着您的数据和宏变得越来越复杂,如果工作表名称反映了工作表内容,它会让生活变得更加轻松。

[ OP注意:我将我的主人wksht重命名为&#39; Combined&#39;并且我的消息来源通过Hub&#39;节点导出节点,并替换了&#39; Sheet1&#39;具有这些名称的常量中的名称。]

我使用WbkDest.Name作为主工作簿的名称。您无需将其更改为实际的工作簿名称。使用这样的属性可以使代码更容易维护,因为如果重命名工作簿,属性值将会更改。

  

我收到运行时错误9下标超出范围错误,当我调试它时,突出显示了设置WshtDest = WbkDest.Worksheets(WshtDestName)。

此段可能超出您目前对VBA的了解。阅读它并提取您的理解。随着您进入阵列和集合,它将变得更加清晰。 WorksheetsCollection或大多数编程语言称之为列表的内容。集合类似于数组,除了您可以在中间添加新值并删除现有值。在数组中,只能通过索引号访问条目,例如:MyArray(5)。集合中的条目可通过索引访问,但集合条目也可以具有key。如果我写了Worksheets(5),那么就会出现错误9,因为没有工作表5.运行宏时,WshtDestName的值为“数据”。没有Worksheets("Data")因此您收到错误9.如果您更新了Const语句,则会出现此错误,因为Worksheets("Sheet1")存在。

  

我不知道开头的常数是否应该在Sub之后,所以我把它们移到Sub下的Dim之后,然后什么也没发生。

在这里你误入了#34; Scope&#34;的主题。如果我在子例程或函数中声明常量或变量,它只在该子例程或函数中可见。常量或变量的“范围”是函数。如果我在模块的顶部声明一个常量或变量,那么该模块中的每个子程序或函数都可以看到它,而不是其他模块中的子程序或函数。常量或变量的“范围”是模块。如果我在声明中添加“Public”,则常量或变量对工作簿中的每个模块或用户表单中的每个子例程或函数都是可见的。常量或变量的“范围”是工作簿。

[来自OP的注释:这很有趣,因为我无法通过Google在Sub之前找到有关常量的信息。谢谢。]

这个工作簿只有一个子程序,只有一个模块,没有用户表单,因此放置常量声明的位置并不重要。常量或变量的最合适范围是一个复杂的问题,我不打算尝试介绍。我只想说这些常量记录了我对工作簿的假设。如果有多个模块,我会将它们定义为Public。

您需要检查我的所有假设。我没有你的数据。我已经编制了我认为与您的数据匹配的数据。但是,如果我对您的数据的任何假设都是错误的,那么宏将无效。

  

当我点击F8查看每行代码时,屏幕提示会显示以下内容:对于Application.ScreenUpdating = False,它会显示Application.ScreenUpdating = True

如果声明为黄色,则表示尚未执行。对于大多数语句,您可以实际修改它,然后再次按 F8 执行它。因此,如果您有一个黄色的A = A + 2,并且您认为:“我的意思是A = A + 3”,您可以在执行前更正该语句。

TrueApplication.ScreenUpdating的默认值,因此这是您在Application.ScreenUpdating = False执行之前看到的值。

  

对于Set WbkDest = ThisWorkbook,屏幕提示表示WbkSet = Nothing和ThisWorkbook =,但只有当黄色突出显示时才会显示这些内容。当按下F8并离开那条线时,当我把光标放在它上面时,它没有说什么。

如果将鼠标悬停在普通变量(数据类型= Long,String,Boolean等)上,解释器将显示其值。对象(例如WbkDest)具有许多属性;翻译应该显示哪个?某些对象(例如Range)具有默认属性。对于Range,这是Value,因此如果将鼠标悬停在某个范围内,则会看到该值。工作簿没有默认属性,因此解释器不显示任何内容。

转到立即窗口并键入? WbkDest.Name,然后单击 Enter 。解释器将显示工作簿的名称。您可以获取显示的任何工作簿属性的值。您还可以显示子属性,例如:WbkDest.Worksheets.CountWbkDest.Worksheets("Sheet1").Range("A1").Value

[ OP注意:第一个错误 - 当我输入&#39;时,我收到了运行时&#39; 424&#39;:对象所需的错误WbkDest.Name&#39;并在立即窗口中按Enter键。它是不是在识别WbkDest,因为它是在开始Dim和后来的Set = This Workbook中声明的。我将名称改为MASTER.xlsm改为MASTER_DESKTOP TEST.xlsm,但这不重要,因为我们从未在此代码中明确提及它,对吗?]

从TD到上述注释的响应 Dim X As Type为X保留一些空间并将其值设置为该类型的默认值。对于Long类型,该值将为零。对于Object类型(Workbook是Object的子类型),默认值为Nothing。没有任何属性,所以在这个阶段? WbkDest.Name会出错。执行语句Set WbkDest = ThisWorkbook后,WbkDest现在可以访问ThisWorkbookThisWorkbook有一个Name,因此? WbkDest.Name会有一个值。你是对的;您可以在不更改代码的情况下重命名工作簿。

  

设置RngDest = .Cells.Find(&#34; *&#34;,。raange(&#34; A1&#34;),xlFormulas ,, xlByRows,xlPrevious)其中RngDest =提示中没有任何内容且没有任何弹出屏幕提示除了-4123(xlFormulas),1(xlByRows)和2(xlPrevious)。

我从中推断出您希望将新数据添加到以前运行宏的数据底部。根据我的经验,这是不寻常的,但为了以防万一,我包含了此选项的代码。

[ OP注意:仅供参考,是的,主人有标题,数据将添加到先前通过宏复制过的数据之下。]

从TD到上述备注的响应我的代码比您需要的更复杂,但包含您想要的功能。如果主工作表为空,则将从第一个源工作表复制标题行和数据行。仅从任何其他工作簿复制数据行。如果主工作表不为空,则仅从源工作表中复制数据行。

xlFormulas,xlByRows和xlPrevious是Excel定义的常量,因此Find的参数是有意义的名称而不是奇怪的数字。

从列出的其他陈述中,我推断出目标工作簿当前是空的。

[注意来自OP:仅供参考,是的,主/目的地wkbk在第一行有一个标题行,但在开始时则为空。]

从TD到上述记录的回复请参阅我的上一个回复。

  

Do FileName&lt;&gt; &#34;&#34;和FileName&lt;&gt; WbkDest.Name,其中FileName和WbkDest.Name =&#34; MASTER.xlsm&#34;在屏幕提示。   F8然后跳过其余的代码到最后的地方   使用WshtDest .Cells.EntireColumn.AutoFit End With等。

此时您已在我的代码中遇到错误。我不明白为什么我的测试没有遇到这个错误。

您需要问:为什么退出循环?为什么没有重复下一个文件?如果我遗漏了大部分代码,你会得到:

Do While FileName <> "" And FileName <> WbkDest.Name
  ‘ Code to process interesting file
  FileName = Dir$
Loop  ' While FileName <> "" And FileName <> WbkDest.Name

FileName <> ""为True,因为FileName =“MASTER.xlsm”但FileName <> WbkDest.Name为False,因为“MASTER.xlsm”= WbkDest.Name。已达到结束条件并且循环结束而不检查任何其他文件。

我应该写:

Do While FileName <> ""
  If FileName <> WbkDest.Name
    ‘ Code to process interesting file
  End If
  FileName = Dir$
Loop  ' While FileName <> ""

使用此代码,工作簿“MASTER.xlsm”会根据需要被忽略,但循环会继续查找更多工作簿。

修改宏以匹配修改后的结构,然后重试。

[ OP注意:第二次错误我收到了编译错误 - 预期:然后或转到,所以我刚刚添加了If If FileName&lt;&gt; WbkDest.Name,所以它读取

If FileName <> WbkDest.Name Then
Set WbkSrc=Workbooks.Open (FolderPath & FileName)
'Rest of Code

这是正确的吗?]

TD对上述备注的回应是的,你是对的。我应该包含测试的代码而不是尝试创建摘要。

[来自OP的说明:第三次错误 - 在我添加了所有编辑后,我在Run下运行了Compile VBA Project并且它说,编译错误:循环没有Do&#39;,我不明白,因为我确定它所指的循环位于底部,并且从来没有一个&#39; Do&#39;在它的旁边。换句话说,我不确定为什么它从来没有出现错误,因为它从来没有“做过”。]

从TD到上述备注的响应编译错误&#34;循环没有Do&#34;,&#34;没有循环&#34;,&#34;如果在结束时如果&#34; ;,&#34;结束如果没有If&#34;等可能会令人困惑。 do循环,for循环和Ifs必须正确嵌套。如果您未能完全完成一个结构,编译器会抱怨外部结构可能是完美的。我的猜测是,您没有为新End If添加If。当编译器命中Loop时,它正在查找End If或嵌套结构的开头。我已用我刚刚测试过的修改过的代码替换了原始代码。您可以复制新代码并更新您的姓名。但是,最好使用你的循环并将其与我的匹配。我的猜测是你会在我的代码中发现End If,而你的代码中没有。{/ p>