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
862 views
in Technique[技术] by (71.8m points)

vba - Reference an excel sheet from another workbook without copying the sheet

Im wondering if it's possible to reference an excel sheet from another work book without making a copy of that sheet?

The situation : I have some very large worksheets filled with various data, but i don't want to keep a copy of them open in my workbooks because while each workbook uses the same data source, they're slightly different.

I have a vba routine that takes this data and creates input files for other codes, vba expects this data to be available on the defined sheet names.

Is it possible to make either excel or vba to know that when i request worksheet("Example_1") it instead knows that i mean example_1 from a different workbook?

Thanks

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

Yes, it is possible.

You need to add those lines to your code:

Dim wkb As Excel.Workbook
Dim wks As Excel.Worksheet

Set wkb = Excel.Workbooks("name_of_workbook.xlsx")
Set wks = wkb.Worksheets("Example_1")

Now, every time you want to refer to a range from this other workbook, you need to add wks. before, i.e.:

'Printing value in cell.
wks.Range("A1") = "x"

'Selecting range.
call wks.Range(wks.Cells(1,1), wks.Cells(2,2)).Select

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

...