Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to activate a workbook that is open using the name of the workbook in VBA

Tags:

excel

vba

I have already a one workbook open but I am running a macro from another workbook. I would like to activate the first workbook using its name.

The code:

FileName = input_path_1 & input_file_1
Workbooks(FileName.xls).Activate

When I try to do so, it is giving me "Subscript out of range" error. How do I solve it?

like image 223
lakshmen Avatar asked Mar 17 '15 07:03

lakshmen


2 Answers

Check if your variable Filename contains the correct filename. (e.g. Sample.xls)
Also check if input_path_1 and input_file_1 have correct values.
If they have it should be like this:

Workbooks(Filename).Activate

Now, if you need to append the extension name (e.g. Filename value is just Sample):

Workbooks(Filename & ".xls").Activate

The argument should always be in the form of string and should be the complete filename (with extension). Although numerals (index) is also accepted, you can't be sure what index refer to what workbook. Better yet, assign it to a variable.

Dim otherWB As Workbook
Set otherWB = Workbooks(Filename)
'Set otherWB = Workbooks(Filename & ".xls") '~~> for second scenario above

Edit1: From comment, if Filename contains the fullpath, then this might work.

Dim Filename1 As String
Filename1 = Split(Filename, "\")(UBound(Split(Filename, "\")))
Workbooks(Filename1).Activate
like image 140
L42 Avatar answered Sep 30 '22 08:09

L42


Only way to access the window of the specific workbook is by below method

Vba

Dim filename as string
set filename = Path.GetFileName(fullFilename)

set Workbook.Windows(filename).WindowState = Excel.XlWindowState.xlMinimized
set Workbook.Windows(filename).WindowState = Excel.XlWindowState.xlNormal

' You can also use Worksheet.Activate() here if you want

C#

string filename;
filename = Path.GetFileName(fullFilename);

Workbook.Windows[filename].WindowState = Excel.XlWindowState.xlMinimized;
Workbook.Windows[filename].WindowState = Excel.XlWindowState.xlNormal;

// you can also use Worksheet.Activate() here if you want
like image 45
Chandraprakash Avatar answered Sep 30 '22 07:09

Chandraprakash