Referring to a range in another workbook with VBA

ChrisA

Board Regular
Joined
May 23, 2002
Messages
50
Hi,

Is it possible to refer to a range in a closed workbook using VBA? I want to write an If Then statement which will depend on the value of a cell in another workbook. Can I do this without opening the other workbook?
 

Excel Facts

Highlight Duplicates
Home, Conditional Formatting, Highlight Cells, Duplicate records, OK to add pink formatting to any duplicates in selected range.
Hi Chris,

Somebody has probably got a better idea, because this seems a bit longwinded, but at least it works. I wasn't able to refer to a range directly, but by entering a formula in a given cell which refers to the data in the closed workbook that you require you can then refer to that. Follow me?
The code below uses cell A1 in Sheet1 of your workbook to temporarily store to data, and then resets A1 to the formula that it previously contained. Obviously you'll need to change the name/path of the source book too.

Anyone got a simpler way? It seems like there should be one.

Sub GetDataFromClosedWorkbook()
Dim sExistingFormula As String
Dim vRequiredValue As Variant

sExistingFormula = Sheet1.Range("A1").Formula
Sheet1.Range("A1").Formula = "='C:\Documents and Settings\My Documents\[Test1.xls]Sheet1'!A1"
vRequiredValue = Sheet1.Range("A1")
Sheet1.Range("A1").Formula = sExistingFormula

MsgBox vRequiredValue
End Sub
 
Upvote 0
thanks tommygun. i am going through it now. i had a question maybe you can help:
i have :
f = "Budget.xls"

i want to replace budget.xls with whats listed in cell E3
so
f = E3

doesnt seem to be working, tried a few combinations. any idea?

cell E3 will list the .xls filename.

thanks.
 
Upvote 0

Forum statistics

Threads
1,216,028
Messages
6,128,400
Members
449,448
Latest member
Andrew Slatter

We've detected that you are using an adblocker.

We have a great community of people providing Excel help here, but the hosting costs are enormous. You can help keep this site running by allowing ads on MrExcel.com.
Allow Ads at MrExcel

Which adblocker are you using?

Disable AdBlock

Follow these easy steps to disable AdBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the icon in the browser’s toolbar.
2)Click on the "Pause on this site" option.
Go back

Disable AdBlock Plus

Follow these easy steps to disable AdBlock Plus

1)Click on the icon in the browser’s toolbar.
2)Click on the toggle to disable it for "mrexcel.com".
Go back

Disable uBlock Origin

Follow these easy steps to disable uBlock Origin

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back

Disable uBlock

Follow these easy steps to disable uBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back
Back
Top