我试图将一系列数据从Excel工作簿复制到另一个工作簿,而不需要在此过程中选择任何工作簿并使用工作表对象名称。
我之所以这么做是因为选择过程:
Windows("SourceWorksheet").Activate - Sheet("SourceSheet").Select - Range("SourceRange").Copy - Windows("DestinationWorksheet").Activate - Sheet("DestinationSheet").Select - Range("DestinationRange").Paste
是非常缓慢的
DestinationWorkBook.DestinationSheet.Range("DestinationRange").Value = SourceWorkBook.SourceWorkSheet.Range("SourceRange").Value
我已经使用纸张、点击名称和字母范围来完成这项工作:
Workbooks(DestinationWorkBook).Sheets("DestinationSheet").Range("A:C").Value = _
Workbooks(SoureceWorkBook).Sheets("SourceSheet").Range("A:C").Value
此外,还使用半动态范围和页的点击名称:
lastRow = Cells(Workbooks(Limits_Name).Sheets("SourceSheet").Rows.Count, _
"A").End(xlUp).Row
Workbooks(DestinationWorkBook).Sheets("DestinationSheet").Range("A1:C" & lastRow).Value = _
Workbooks(SourceWorkBook).Sheets("SourceSheet").Range("A1:C" & lastRow).Value
当我使用工作表对象名称而不是工作表名称或单元格而不是范围时,我的问题就开始了。在这种情况下,当我得到那个错误时:
Workbooks(DestinationWorkBook).shtDestinationSheet.Range("A:C").Value = _
Workbooks(SourceWorkBook).Sheets("SourceSheet").Range("A:C").Value
OR
lastRow = Cells(Workbooks(SourceWorkBook).Sheets("SourceSheet").Rows.Count, "A").End(xlUp).Row
lastCol = Cells(1, Workbooks(SourceWorkBook).Sheets("SourceSheet").Columns.Count).End(xlToLeft).Column
Workbooks(DestinationWorkBook).Sheets("DestinationSheet").Range(Cells(1, 1), Cells(lastRow, lastCol)).Value = _
Workbooks(SourceWorkBook).Sheets("SourceSheet").Range(Cells(1, 1), Cells(lastRow, lastCol)).Value
OR (this is the ideal code)
lastRow = Cells(Workbooks(SourceWorkBook).Sheets("SourceSheet").Rows.Count, "A").End(xlUp).Row
lastCol = Cells(1, Workbooks(SourceWorkBook).Sheets("SourceSheet").Columns.Count).End(xlToLeft).Column
Workbooks(DestinationWorkBook).shtDestinationSheet.Range(Cells(1, 1), Cells(lastRow, lastCol)).Value = _
Workbooks(SourceWorkBook).Sheets("SourceSheet").Range(Cells(1, 1), Cells(lastRow, lastCol)).Value
我想知道使用工作表(“sheetname”)和工作表对象属性的( name )属性下的工作表对象名称和工作表对象名称之间的区别。
如果我使用sheet (“SourceSheet”).Range(“”),我不需要选择工作表,而是使用sthSourceSheet.Range("")来选择。
我喜欢使用工作表对象名,因为如果工作表名称被修改,VBA代码仍然有效。
发布于 2015-11-12 13:20:33
第一个问题(已解决):
当为Worksheet
使用对象时,这也包括Workbook
。虽然Worksheet-Object
不是工作簿本身在语法(如Workbook.Worksheet_Object
)中的子类。所以要么使用Workbook.Worksheet(Worksheet_Object.Name)
,要么只使用Worksheet_Object
第二步(已解决):
在非活动工作簿中使用Range(Cells(), Cells())
存在问题.只使用没有父级的Cells()
有时会带来麻烦,因为VBA想要使用完整的路径。只有Cells
会在与不同的父级一起使用时重新设置一个workbookSheet!范围,这会导致错误。VBA将得到一个类似于:Wb1.Ws1.Range(Wb2.Ws2.Range)
的返回。
你可以尝试这样的方法:
htDestinationSheet.Range(htDestinationSheet.Cells(1, 1), htDestinationSheet.Cells(lastRow, lastCol)).Value = Workbooks(SourceWorkBook).Sheets("SourceSheet").Range(Workbooks(SourceWorkBook).Sheets("SourceSheet").Cells(1, 1), Workbooks(SourceWorkBook).Sheets("SourceSheet").Cells(lastRow, lastCol)).Value
这应该管用..。然而:我认为留在str
(看起来更好)更好。
https://stackoverflow.com/questions/33670584
复制相似问题