如何使用 Excel VBA 从使用文件浏览器选择的工作簿中复制工作表?

How do I use Excel VBA to copy a worksheet from a workbook selected using a file browser?

我正在尝试创建我认为应该非常简单的宏。我每天处理同一份报告,每天早上都会更新。也就是说,如果能够将我昨天处理的数据与给定早晨的新数据放在同一个工作簿中,那将是非常好的。

基本上,我想要做的就是使用文件浏览器将另一个工作簿(包含昨天报告的那个)的工作表复制到我的活动工作簿(包含今天报告的那个)中。

Application.GetOpenFilename 方法打开了我想要的文件浏览器,但我不知道如何使用它 returns 复制到我想要的工作表中的目录字符串。

这是我一直在使用的代码:

Sub Macro5()

Dim todayWBName As String
Dim yesterdayWB As Workbook
Set todayWB = ActiveWorkbook
todayWBName = todayWB.Name

'open file from last business day
    yesterdayWBName = Application.GetOpenFilename( _
                      Title:="Select backorder file from last business day", _
                      MultiSelect:=False)
    If yesterdayWBName = False Then
        Exit Sub
    Else
        End If
    Workbooks.Open yesterdayWBName
    Set yesterdayWB = ActiveWorkbook
    todayWB.Activate

'copy in yesterday's info
    yesterdayWB(1).Copy After:=todayWB.Sheets(1)
    yesterdayWB.Close
    Sheets("Sheet 1 (2)").Name = "YesterdayResolution"
    Sheets(1).Activate

End Sub

如果有人能告诉我我做错了什么,我将不胜感激。

提前致谢。

试试这个。使用来自 GetOpenFileName 的字符串结果并将其直接传递给 Workbooks.Open 方法,将 return 值作为分配给 yesterdayWB 对象的对象(工作簿)处理。

另外,你有一个错误:

yesterdayWB(1).Copy After:=todayWB.Sheets(1)

工作簿对象不可订阅,你的意思(我认为)是 yesterdayWB.Worksheets(1).Copy ...

Sub Macro5()

    Dim yesterdayWB As Workbook
    Dim yesterdayWBName As String
    Dim todayWB As Workbook

    Set todayWB = ActiveWorkbook

    'open file from last business day
    yesterdayWBName = Application.GetOpenFilename( _
                      Title:="Select backorder file from last business day", _
                      MultiSelect:=False)
    If yesterdayWBName = False Then
        Exit Sub
    End If
    Set yesterdayWB = Workbooks.Open(yesterdayWBName)

    'copy in yesterday's info
    yesterdayWB.Worksheets(1).Copy After:=todayWB.Sheets(1)
    yesterdayWB.Close
    ' the sheet you copied is at index "2" because you put it after Sheets(1)
    todayWB.Sheets(2).Name = "YesterdayResolution"
    todayWB.Sheets(1).Activate

End Sub