[英]How do I use Excel VBA to copy a worksheet from a workbook selected using a file browser?
I'm trying to create what I thought should be a really simple Macro. 我试图创建我认为应该是一个非常简单的宏。 I deal with the same report every day, which is updated each morning.
我每天处理同一份报告,每天早晨更新。 That said, it would be really nice for me to be able to have the data I worked with yesterday in the same workbook as the new data from a given morning.
就是说,对于我来说,能够将与昨天一起使用的数据与给定早晨的新数据保存在同一工作簿中对我来说真的很高兴。
Basically, all I want to do is copy a worksheet from a different workbook (the one with yesterday's report) into my active workbook (the one with today's report) using a file browser. 基本上,我要做的就是使用文件浏览器将一个工作表从另一个工作簿(具有昨天报告的工作表)复制到我的活动工作簿(具有今天报告的工作表)中。
The Application.GetOpenFilename method opens up a file browser like what I want, but I can't figure out how to use the directory string that it returns to copy in the worksheet I want. Application.GetOpenFilename方法可以像我想要的那样打开文件浏览器,但是我不知道如何使用返回的目录字符串复制到我想要的工作表中。
Here's the code I've been using: 这是我一直在使用的代码:
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
If anyone could tell me what I'm doing wrong here, I'd really appreciate it. 如果有人能告诉我我在做什么错,我将非常感激。
Thanks in advance. 提前致谢。
Try this. 尝试这个。 Use the string result from the
GetOpenFileName
and pass it directly to the Workbooks.Open
method, handling the return value as an object (workbook) which assigns to yesterdayWB
object. 使用
GetOpenFileName
的字符串结果并将其直接传递给Workbooks.Open
方法,将返回值作为分配给yesterdayWB
对象的对象(工作簿)进行处理。
Also, you have an error: 另外,您有一个错误:
yesterdayWB(1).Copy After:=todayWB.Sheets(1)
The workbook object is not subscriptable, what you meant (I think) was yesterdayWB.Worksheets(1).Copy ...
该工作簿对象不可下标,您的意思(我认为)是
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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.