【问题标题】:Error 5 using Dir - Macro to copy a sheet from another workbook, using sheetname错误 5 使用 Dir - 使用工作表名称从另一个工作簿复制工作表的宏
【发布时间】:2016-12-06 17:33:01
【问题描述】:

我今天一直被困在这个问题上......

我有一个包含多个 .xlsx 文件的文件夹,名为“要修改的文件” 它们中的每一个都有其第一张特别命名的工作表,例如“test1”。

我有另一个文件夹,其中包含其他名为“要插入的旧文件”的 .xlsx 文件 其中的每一个都像这样专门调用:“old test1.xlsx”、old test2 等......

我希望我的宏遍历第一个文件夹和文件,并将相应旧 .xlsx 的第一张表复制到另一个文件夹中。

代码远没有工作,但主要问题是我在 Dir 行上收到错误 5,我认为这是因为我使用了 dir 两次(ProcessFiles 宏在我不需要的另一种情况下工作正常在 DoWork 子中使用 Dir)。

欢迎任何帮助,因为您可以猜到我是初学者。

这是我的代码

Sub ProcessFiles()

Dim FileName, Pathname As String
Dim wb As Workbook

Pathname = ActiveWorkbook.Path & "\Files to modify\"
FileName = Dir(Pathname & "*.xlsx", vbNormal)

Do While FileName <> ""

Set wb = Workbooks.Open(FileName:=Pathname & FileName, Local:=True)
DoWork wb
wb.Close True


Set wb = Nothing
FileName = Dir 'Error 5 is here

Loop

End Sub

Sub DoWork(wb As Workbook)
Dim FileName As String

FileName = Dir(ActiveWorkbook.Path & "\Old file to insert\" & "old " & ActiveSheet.Name & ".xlsx")


If FileName = "" Then
MsgBox "File does not exist"
Else
Set wb2 = Application.Workbooks.Open(FileName)
wb2.Sheets(1).Copy After:=wb.Sheets(1)

End If
End Sub

【问题讨论】:

  • Dir 是一个函数,你不能像= 那样设置它,检查你是如何在FileName = Dir(Pathname &amp; "*.xlsx", vbNormal) 行中转换它的-这里它有工作所需的参数-。
  • 谢谢你们的帮助:)

标签: vba excel


【解决方案1】:

正如您所料,在两个不同的地方同时使用Dir 是在找麻烦。

在子DoWork 中,您仅用于检查文件是否存在。这个不用你用,可以直接尝试打开W​​orkbook,看看是否打开成功..

Sub DoWork(wb As Workbook)
    Dim FileName As String
    ' Dont use Dir here
    Filename = ActiveWorkbook.Path & "\Old file to insert\" & "old " & ActiveSheet.Name & ".xlsx"  

    'Try to open the file if it exists, otherwise handle the error
    On Error Resume Next
    Set wb2 = Application.Workbooks.Open(Filename)
    If Err.Number <> 0 Then
        MsgBox "File does not exist or could not open"
    Else
          ' Now the file is open, continue work with it
          wb2.Sheets(1).Copy After:=wb.Sheets(1)
    End If
End Sub

【讨论】:

  • 你好 ASH。谢谢那很聪明并且完成了工作!祝你愉快
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-03-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-07-09
相关资源
最近更新 更多