Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
337 views
in Technique[技术] by (71.8m points)

Excel VBA, getting range from an inactive sheet

This script works fine when I'm viewing the "Temp" sheet. But when I'm in another sheet then the copy command fails.. It gives a "Application-defined or object-defined error"

Sheets("Temp").Range(Cells(1), Cells(1).End(xlDown)).Copy
Sheets("Overview").Range("C40").PasteSpecial

I can use this script instead, but then I have problems with pasting it

Sheets("Temp").Columns(1).Copy
Sheets("Overview").Range("C40").PasteSpecial
  • I dont want to activate the "Temp" sheet to get this

What else can I do

question from:https://stackoverflow.com/questions/8047943/excel-vba-getting-range-from-an-inactive-sheet

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Your issue is that the because the Cell references inside the Range 's are unqualified, they refer to a default sheet, which may not be the sheet you intend. For standard modules, the ThisWorkbook module, custom classes and user form modules, the defeault is the ActiveSheet. For Worksheet code behind modules, it's that worksheet.

For modules other than worksheet code behind modules, your code is actually saying

Sheets("Temp").Range(ActiveSheet.Cells(1), ActiveSheet.Cells(1).End(xlDown)).Copy
Sheets("Overview").Range("C40").PasteSpecial

For worksheet code behind modules, your code is actually saying

Sheets("Temp").Range(Me.Cells(1), Me.Cells(1).End(xlDown)).Copy
Sheets("Overview").Range("C40").PasteSpecial

In either case, the solution is the same: fully qualify the range references with the required workbook:

Dim sh1 As Worksheet
Dim sh2 As Worksheet

Set sh1 = ActiveWorkbook.Sheets("Temp")
Set sh2 = ActiveWorkbook.Sheets("Overview")

With sh1
    .Range(.Cells(1,1), .Cells(1,1).End(xlDown)).Copy
End With
sh2.Range("C40").PasteSpecial

Note: When using .End(xlDown) there is a danger that this will result in a range extending further than you expect. It's better to use .End(xlUp) if your sheet layout allows. If not, check the referenced cell and the cell below for Empty first.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...