PDA

View Full Version : Solved: Open a file in automatic



Nicolaf
12-11-2012, 02:46 AM
Hi,

I have the following code for opening files:



Sub Open_file()
Iname = Range("B2").Value 'name with extension
Workbooks.Open Filename:="P:\General\Files\" & Iname
Sheets("Sheet2").select
End Sub



I would now like to change the code so the part that refers to Sheet2 is actually a Cell reference eg. cell B4
This way the file will open the sheet name that I put in Cell B4 (eg. Sheet3 or Sheet4 etc.) rather than having something hardcoded in code.

How do I do this?

:dunno :dunno

Nix

p45cal
12-11-2012, 03:48 AM
Range("B2").Value
is unqualified, that is, it doesn't specify what sheet B2 is on; if the code is in a worksheet code-module, it is on that worksheet, if the code is anywhere else, it is on the active sheet.
So depending on where the code is you may have to qualify it (what's more, if you're opening a workbook and it has sheet names which are the same as the already open workbook you may further have to qualify the workbook.
However you choose to qualify Range("B2").Value, you need similarly to qualify Range("B4").Value when getting the sheet name.Sub Open_file()
IName = ThisWorkbook.Sheets("Sheet1").Range("B2").Value 'name with extension
Set NewWkbk = Workbooks.Open(Filename:="P:\General\Files\" & IName)
SName = ThisWorkbook.Sheets("Sheet1").Range("B4").Value 'sheet name
NewWkbk.Sheets(SName).Select
End Sub
orSub Open_file()
With ThisWorkbook.Sheets("Sheet1")
IName = .Range("B2").Value 'name with extension
Set NewWkbk = Workbooks.Open(Filename:="P:\General\Files\" & IName)
SName = .Range("B4").Value 'sheet name
NewWkbk.Sheets(SName).Select
End With
End SubAll untested.

Nicolaf
12-11-2012, 03:56 AM
Great it works!

Txs,
Nix
:hi: :yes