我已经看到了这些问题的答案,这些是我正在寻找的变体,但是当我尝试根据我的情况修改代码时,我不断收到错误消息。
我有两个工作簿,一个主“模板”和一个名为“YTDJune2015”的月度报告。每个都有15张相同的两张纸,我想将每月报告中的数据复制到模板中,该模板具有计算15个独特表格中每一个的附加数据的公式。我想使用“打开”对话框作为选择源工作簿的方法,因为报告每月更新一次。在打开对话框中选择源文档后,我不断收到错误“Object Required”,并且无法弄清楚如何允许它打开源工作簿。代码的范围部分也可能不正确,但我无法通过源文档的打开,所以我无法检查它。我希望它遍历源工作簿中的每个工作表并复制相同的范围,然后粘贴到目标工作簿。到目前为止,我的代码是:
Sub UpdateWorkbook()
Dim wbSource As Workbook, wbDest As Workbook
Dim ws As Worksheet, rng As Range
Application.ScreenUpdating = False
Set wbSource = Application.GetOpenFilename(FileFilter:="Excel Filter (*.xlsx), *.Xlsx", Title:="Open File(s)", MultiSelect:=False)
Set wbDest = Workbooks.Open("Template.xlsm")
For Each ws In wbSource.Sheets
For Each rng In ws.Range("C8:AB117").Areas
wbDest.Sheets(ws.Name).Range(rng.Address).Value = rng.Value
Next rng
Next ws
wbSource.Close SaveChanges:=False
Application.ScreenUpdating = True
End Sub
答案 0 :(得分:1)
<强>未测试强>
Sub UpdateWorkbook()
Dim wbSource As Workbook, wbDest As Workbook
Dim ws As Worksheet, rng As Range
Dim sFile As String
Application.ScreenUpdating = False
sFile = Application.GetOpenFilename(FileFilter:="Excel Filter (*.xlsx), *.Xlsx", Title:="Open File(s)", MultiSelect:=False)
Set wbSource = Workbooks.Open(sFile)
Set wbDest = Workbooks.Open("Template.xlsm") 'path missing?
For Each ws In wbSource.Sheets
wbDest.Sheets(ws.name).Range("C8:AB117").Value2 = ws.Range("C8:AB117").Value2 'change range?
Next ws
wbSource.Close SaveChanges:=False
Application.ScreenUpdating = True
End Sub
答案 1 :(得分:0)
上述评论者对GetOpenFilename
是正确的,它不返回Workbook
个对象,它返回的字符串是您选择的文件的路径,因此&#34; Object Required&#34 ;
要解决此问题,我建议使用Dimming一个字符串来包含文件名,然后将工作簿对象设置为新的变量名,如注释中所示。
我想添加的内容是最后一部分,您可以在代码中使用粘贴特殊值:
Sub UpdateWorkbook()
Dim wbSource As Workbook, wbDest As Workbook
Dim ws As Worksheet, rng As Range
Dim sFile as String
Application.ScreenUpdating = False
sFile = Application.GetOpenFilename(FileFilter:="Excel Filter (*.xlsx), *.Xlsx", Title:="Open File(s)", MultiSelect:=False)
Set wbSource = Workbooks.Open(sFile)
Set wbDest = Workbooks.Open("Template.xlsm")
For Each ws In wbSource.Sheets
For Each rng In ws.Range("C8:AB117").Areas
rng.copy
wbDest.Sheets(ws.Name).Range(rng.Address).PasteSpecial xlPasteValues
Next rng
Next ws
Application.CutCopyMode = False
wbSource.Close SaveChanges:=False
Application.ScreenUpdating = True
End Sub
但是,您可能希望将xlPasteValues
更改为xlPasteValuesAndNumberFormats