如何激活使用 VBA 中工作簿名称打开的工作簿

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/29093238/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-08 09:28:56  来源:igfitidea点击:

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

excelvbaexcel-vba

提问by lakesh

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?

当我尝试这样做时,它给了我“下标超出范围”错误。我该如何解决?

回答by L42

Check if your variable Filenamecontains the correct filename. (e.g. Sample.xls)
Also check if input_path_1and input_file_1have correct values.
If they have it should be like this:

检查您的变量是否Filename包含正确的文件名。(如Sample.xls
同时检查input_path_1input_file_1有正确的价值观。
如果他们有它应该是这样的:

Workbooks(Filename).Activate

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

现在,如果您需要附加扩展名(例如,Filename值只是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 Filenamecontains the fullpath, then this might work.

Edit1:从评论中,如果Filename包含完整路径,那么这可能有效。

Dim Filename1 As String
Filename1 = Split(Filename, "\")(UBound(Split(Filename, "\")))
Workbooks(Filename1).Activate

回答by Chandraprakash

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

访问特定工作簿窗口的唯一方法是通过以下方法

Vba

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#

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