【问题标题】:Import sheet from one excel file to another without specifying destination将工作表从一个 Excel 文件导入到另一个而不指定目的地
【发布时间】:2019-07-30 13:46:13
【问题描述】:

需要将 Excel 工作簿导入现有 Excel 启用宏的工作簿的工作表

已使用指定目标的代码成功导入我使用“.xlsx”作为目标,因为“*”用于指定文件夹中找到的所有 xlsx 文件。

Sub CopySheets()

    Dim WB As Workbook
    Dim SourceWB As Workbook
    Dim WS As Worksheet    
    Dim ASheet As Worksheet

    'Turns off screenupdating and events:    
    Application.ScreenUpdating = False   
Application.EnableEvents = False

'Sets the variables:
Set WB = ActiveWorkbook
Set ASheet = ActiveSheet
Set SourceWB = Workbooks.Open(WB.Path & "\*.xlsx")  'Modify to match

'Copies each sheet of the SourceWB to the end of original wb:
For Each WS In SourceWB.Worksheets
    WS.Copy after:=WB.Sheets(WB.Sheets.Count)
Next WS        
    SourceWB.Close savechanges:=False
    Set WS = Nothing
    Set SourceWB = Nothing       
WB.Activate
ASheet.Select
    Set ASheet = Nothing
    Set WB = Nothing        
Application.EnableEvents = True

End Sub

错误是“运行时错误'1004':抱歉,我们找不到 C:\Users\ZMOLD01\Desktop\CaseStudy Results*.xlsx。它可能被移动、重命名或删除了吗?

【问题讨论】:

  • 使用Dir 函数。你不能在Workbooks.Open 中使用这样的通配符。请参阅this question 了解如何操作。
  • 您发送的只是打开文件本身而不是将其导入当前的Excel工作表中。

标签: excel vba


【解决方案1】:

Dir 会为您提供在目标中找到的文件名。

更改:

Set SourceWB = Workbooks.Open(WB.Path & "\*.xlsx") 

收件人:

If Len(Dir(wb.path & "\*.xlsx")) > 0 Then

    Set SourceWB = Workbooks.Open(wb.path & "\" & Dir(wb.path & "\*.xlsx"))

Else: Msgbox "File Not Found"
End if

【讨论】:

  • 在“对于 SourceWB.Worksheets 中的每个 WS”行中出现“对象变量或未设置块变量”的错误
  • msgbox 出现了吗?
  • 是的,它出现了,没有任何内容被复制到我当前的文件中
  • 然后找不到文件。这就是为什么 msgbox 出现了。您确定文件格式为 Results*.xlsx 吗?并在与当前工作簿相同的文件夹中?
  • 在我当前使用的 excel 文件的位置只有 1 个 .xlsx 文件,我需要自动检测到它,以便将其复制到我使用的 excel 文件中
猜你喜欢
  • 2013-10-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-07-22
  • 1970-01-01
  • 2020-11-20
  • 1970-01-01
相关资源
最近更新 更多