Как активировать окно excel vba

Содержание

  1. Оператор AppActivate
  2. Синтаксис
  3. Замечания
  4. Пример
  5. См. также
  6. Поддержка и обратная связь
  7. Vba как активировать окно excel
  8. AppActivate statement
  9. Syntax
  10. Remarks
  11. Example
  12. See also
  13. Support and feedback
  14. Two ways to activate a program with VBA if already open
  15. The VBA Tutorials Blog
  16. Introduction
  17. Method 1 — AppActivate
  18. Tutorial
  19. Method 2 — explorer.exe Folders
  20. Tutorial
  21. Closing Thoughts

Оператор AppActivate

Делает активным окно приложения.

Синтаксис

AppActivatetitle, [ wait ]

Синтаксис оператора AppActivate состоит из следующих именованных аргументов:

Part Описание
заголовок Обязательно. Строковое выражение, указывающее заголовок в строке заголовка окна приложения, которое необходимо сделать активным. Для активации приложения на месте заголовка может использоваться идентификатор задачи, возвращаемый функцией Shell.
wait Необязательный параметр. Логическое значение, указывающее наличие фокуса в вызывающем приложении перед активацией другого. При значении False (по умолчанию) указанное приложение сразу становится активным, даже если вызывающее приложение не имеет фокуса. Если задано значение True, вызывающее приложение ожидает, пока оно не перейдет в фокус, а затем активирует указанное приложение.

Замечания

Оператор AppActivate перемещает фокус на именованное приложение или окно, но не влияет на его размер. Если пользователь выполняет некоторые действия, чтобы изменить фокус или закрыть окно, фокус перемещается с окна активированного приложения. Для запуска приложения и выбора стиля окна используйте функцию Shell.

В определении того, какое приложение сделать активным, title сравнивается со строкой заголовка каждого запущенного приложения. Если точного соответствия нет, активируется любое приложение, строка заголовка которого начинается с title. Если сразу несколько приложений имеют имя title, одно из них активизируется произвольным образом.

Пример

В этом примере показаны различные варианты использования оператора AppActivate для активации окна приложения. Операторы оболочки предполагают, что приложения находятся по указанным путям. В macOS диск по умолчанию обозначается «HD», а части аргумента «путь» отделяются друг от друга двоеточиями вместо обратной косой черты.

См. также

Поддержка и обратная связь

Есть вопросы или отзывы, касающиеся Office VBA или этой статьи? Руководство по другим способам получения поддержки и отправки отзывов см. в статье Поддержка Office VBA и обратная связь.

Источник

Vba как активировать окно excel

Доброго времени суток! Есть один небольшой скрипт, суть его работы:

1) есть основной файл «1.xlsm», в который внесены данные для заполнения шаблоном документов на основании заранее подготовленных значений (заполнение значительной части документов производится в Word на основании сопоставления «Закладок» в этом приложении), т.е. этот скрипт копирует файл из одного каталога в другой с внесением в него определённых значений в заранее вставленные «Закладки» файла Word

скрипт находится в файле «1.xlsm»

2) после выполнения скрипта получается 3 файла:
— «1.xlsm» со скриптом
— исходный шаблон «. .doc» размещён в одном каталоге (адрес данного файла указан в ячейке C30 файла «1.xlsm»)
— новый файл «. .doc» помещается в другом каталоге (адрес данного файла указан в ячейке C33 файла «1.xlsm»)

3) по итогу:
— активируется окно приложения Word и открывается окно «Проводника», где сохранён новый файл. далее сотрудник, которому нужен заполненный шаблон переносит его куда-то в другой каталог (или отправляет кому-то на почту), т.е. по своему усмотрению

Но появились шаблоны некоторых документов и в Excel, в не Word, для которых я сделал похожий скрипт (текст ниже) и возникли небольшие проблемы при его выполнении:

1) код «objExcel.Application.Visible = False» должен скрывать окно программы Excel при внесении данных, но окно Excel появляется на 1-2 секунды и потом закрывается

2) код «Workbooks(2).ActivateActive» и «Window.WindowState = xlMaximized» должен активировать окно с новым файлом Excel, но активации окна не производится. код «Windows(«. xls»).Activate» не подходит, т.к. имя новой таблицы может меняться и указано это только в ячейке C31 файла «1.xlsm», т.е. вручную каждый раз прописывать не вариант

Помогите, пожалуйста, разобраться с этими проблемками .

Скрины и текст скрипта прилагаю, вложить сам файл не могу, т.к. там рабочая база

Sub obj2() ‘скрипт копирования файла excel из таблицы excel и заполнение ячеек на основании таблицы excel

Dim objExcel As Object
Dim FileStart
Dim FileNew

‘обновление ячейки для добавления времени в имя файла
Range(«E29»).FormulaR1C1 = «=NOW()»

Set objExcel = CreateObject(«Excel.Application»)

‘исходный файл (шаблон), можно указать путь «g:2.xlsx» или «\fuib.comkhoDOCUMENTYOOKUTU. «
FileSt = Range(«C30»).Value

‘новый файл, можно указать путь «g:5.xlsx» или «\fuib.comkhoDOCUMENTYOOKUTU. «
FileNew = Range(«C33»).Value

Set objWorkbook = Workbooks.Open(FileSt)

‘если написать objExcel.Application.Visible = True, то Шаблон появляться будет
objExcel.Application.Visible = False

‘ описание файлов при сохранении https://www.mrexcel.com/board. 759381
ActiveWorkbook.SaveAs _
Filename:=FileNew, _
FileFormat:=xlOpenXMLWorkbook, _
CreateBackup:=False
objExcel.Quit

‘открытие нового файла
Dim objExcelApp As Object
Set objExcel = CreateObject(«Excel.Application»)
Set objWorkbook = Workbooks.Open(FileNew)
objExcel.Visible = True ‘если написать oobjExcel.Visible = False, то Шаблон появляться не будет

‘активация окна нового файла
Workbooks(2).Activate
ActiveWindow.WindowState = xlMaximized

‘пауза 2 сек.
Application.Wait (Now() + TimeValue(«00:00:02»))

‘открытие «Проводника» в папке; источник https://vremya-ne-zhdet.ru/vba-exc. vodnike
Shell «cmd /C start «»»» «»\fuib.comkhoDOCUMENTYOOKUTUКулиничев! открытие счетовavtoготовые документы»»», vbNormalFocus

Доброго времени суток! Есть один небольшой скрипт, суть его работы:

1) есть основной файл «1.xlsm», в который внесены данные для заполнения шаблоном документов на основании заранее подготовленных значений (заполнение значительной части документов производится в Word на основании сопоставления «Закладок» в этом приложении), т.е. этот скрипт копирует файл из одного каталога в другой с внесением в него определённых значений в заранее вставленные «Закладки» файла Word

скрипт находится в файле «1.xlsm»

2) после выполнения скрипта получается 3 файла:
— «1.xlsm» со скриптом
— исходный шаблон «. .doc» размещён в одном каталоге (адрес данного файла указан в ячейке C30 файла «1.xlsm»)
— новый файл «. .doc» помещается в другом каталоге (адрес данного файла указан в ячейке C33 файла «1.xlsm»)

3) по итогу:
— активируется окно приложения Word и открывается окно «Проводника», где сохранён новый файл. далее сотрудник, которому нужен заполненный шаблон переносит его куда-то в другой каталог (или отправляет кому-то на почту), т.е. по своему усмотрению

Но появились шаблоны некоторых документов и в Excel, в не Word, для которых я сделал похожий скрипт (текст ниже) и возникли небольшие проблемы при его выполнении:

1) код «objExcel.Application.Visible = False» должен скрывать окно программы Excel при внесении данных, но окно Excel появляется на 1-2 секунды и потом закрывается

2) код «Workbooks(2).ActivateActive» и «Window.WindowState = xlMaximized» должен активировать окно с новым файлом Excel, но активации окна не производится. код «Windows(«. xls»).Activate» не подходит, т.к. имя новой таблицы может меняться и указано это только в ячейке C31 файла «1.xlsm», т.е. вручную каждый раз прописывать не вариант

Помогите, пожалуйста, разобраться с этими проблемками .

Скрины и текст скрипта прилагаю, вложить сам файл не могу, т.к. там рабочая база

Sub obj2() ‘скрипт копирования файла excel из таблицы excel и заполнение ячеек на основании таблицы excel

Dim objExcel As Object
Dim FileStart
Dim FileNew

‘обновление ячейки для добавления времени в имя файла
Range(«E29»).FormulaR1C1 = «=NOW()»

Set objExcel = CreateObject(«Excel.Application»)

‘исходный файл (шаблон), можно указать путь «g:2.xlsx» или «\fuib.comkhoDOCUMENTYOOKUTU. «
FileSt = Range(«C30»).Value

‘новый файл, можно указать путь «g:5.xlsx» или «\fuib.comkhoDOCUMENTYOOKUTU. «
FileNew = Range(«C33»).Value

Set objWorkbook = Workbooks.Open(FileSt)

‘если написать objExcel.Application.Visible = True, то Шаблон появляться будет
objExcel.Application.Visible = False

‘ описание файлов при сохранении https://www.mrexcel.com/board. 759381
ActiveWorkbook.SaveAs _
Filename:=FileNew, _
FileFormat:=xlOpenXMLWorkbook, _
CreateBackup:=False
objExcel.Quit

‘открытие нового файла
Dim objExcelApp As Object
Set objExcel = CreateObject(«Excel.Application»)
Set objWorkbook = Workbooks.Open(FileNew)
objExcel.Visible = True ‘если написать oobjExcel.Visible = False, то Шаблон появляться не будет

‘активация окна нового файла
Workbooks(2).Activate
ActiveWindow.WindowState = xlMaximized

‘пауза 2 сек.
Application.Wait (Now() + TimeValue(«00:00:02»))

‘открытие «Проводника» в папке; источник https://vremya-ne-zhdet.ru/vba-exc. vodnike
Shell «cmd /C start «»»» «»\fuib.comkhoDOCUMENTYOOKUTUКулиничев! открытие счетовavtoготовые документы»»», vbNormalFocus

Сообщение Доброго времени суток! Есть один небольшой скрипт, суть его работы:

1) есть основной файл «1.xlsm», в который внесены данные для заполнения шаблоном документов на основании заранее подготовленных значений (заполнение значительной части документов производится в Word на основании сопоставления «Закладок» в этом приложении), т.е. этот скрипт копирует файл из одного каталога в другой с внесением в него определённых значений в заранее вставленные «Закладки» файла Word

скрипт находится в файле «1.xlsm»

2) после выполнения скрипта получается 3 файла:
— «1.xlsm» со скриптом
— исходный шаблон «. .doc» размещён в одном каталоге (адрес данного файла указан в ячейке C30 файла «1.xlsm»)
— новый файл «. .doc» помещается в другом каталоге (адрес данного файла указан в ячейке C33 файла «1.xlsm»)

3) по итогу:
— активируется окно приложения Word и открывается окно «Проводника», где сохранён новый файл. далее сотрудник, которому нужен заполненный шаблон переносит его куда-то в другой каталог (или отправляет кому-то на почту), т.е. по своему усмотрению

Но появились шаблоны некоторых документов и в Excel, в не Word, для которых я сделал похожий скрипт (текст ниже) и возникли небольшие проблемы при его выполнении:

1) код «objExcel.Application.Visible = False» должен скрывать окно программы Excel при внесении данных, но окно Excel появляется на 1-2 секунды и потом закрывается

2) код «Workbooks(2).ActivateActive» и «Window.WindowState = xlMaximized» должен активировать окно с новым файлом Excel, но активации окна не производится. код «Windows(«. xls»).Activate» не подходит, т.к. имя новой таблицы может меняться и указано это только в ячейке C31 файла «1.xlsm», т.е. вручную каждый раз прописывать не вариант

Помогите, пожалуйста, разобраться с этими проблемками .

Скрины и текст скрипта прилагаю, вложить сам файл не могу, т.к. там рабочая база

Sub obj2() ‘скрипт копирования файла excel из таблицы excel и заполнение ячеек на основании таблицы excel

Dim objExcel As Object
Dim FileStart
Dim FileNew

‘обновление ячейки для добавления времени в имя файла
Range(«E29»).FormulaR1C1 = «=NOW()»

Источник

AppActivate statement

Activates an application window.

Syntax

AppActivate title, [ wait ]

The AppActivate statement syntax has these named arguments:

Part Description
title Required. String expression specifying the title in the title bar of the application window you want to activate. The task ID returned by the Shell function can be used in place of title to activate an application.
wait Optional. Boolean value specifying whether the calling application has the focus before activating another. If False (default), the specified application is immediately activated, even if the calling application does not have the focus. If True, the calling application waits until it has the focus, and then activates the specified application.

The AppActivate statement changes the focus to the named application or window but does not affect whether it is maximized or minimized. Focus moves from the activated application window when the user takes some action to change the focus or close the window. Use the Shell function to start an application and set the window style.

In determining which application to activate, title is compared to the title string of each running application. If there is no exact match, any application whose title string begins with title is activated. If there is more than one instance of the application named by title, one instance is arbitrarily activated.

Example

This example illustrates various uses of the AppActivate statement to activate an application window. The Shell statements assume that the applications are in the paths specified. On the Macintosh, the default drive name is «HD» and portions of the pathname are separated by colons instead of backslashes.

See also

Support and feedback

Have questions or feedback about Office VBA or this documentation? Please see Office VBA support and feedback for guidance about the ways you can receive support and provide feedback.

Источник

Two ways to activate a program with VBA if already open

The VBA Tutorials Blog

Introduction

If you’re a follower of the wellsr.com VBA Tutorials Blog, you already know how to open a program, file or folder with the VBA Shell command. But, let’s say you have a program that opens a file and you run it again. What happens? A new instance of the program annoyingly appears.

Wouldn’t it be great if, instead of opening a new instance, you could activate an application that you previously opened? Today, I’ll show you two ways to do just that — keep reading to discover how!

  • Method 1 will teach you how to reactivate a previously opened program using the AppActivate function. This will work for all programs and applications, except for those opened using explorer.exe. Again, this will not work to open folders you originally opened with explorer.exe. See Method 2 for ways to work with folders.
  • Method 2 will show you how to reactivate windows explorer folders you previously opened with explorer.exe. For example, you can use it to reactivate an existing My Documents window instead of opening a new instance.

July 2018 Update: The original Method 2 OpenExplorer macro would reactivate windows explorer folders, but it wouldn’t bring them to the foreground if the folders were minimized. The macro for activating Windows Explorer was improved during this update and now gives you complete control over opening and activating folders using VBA.

These two methods are adaptations of the concepts introduced in my article on opening and closing files with VBA Shell. If you want to learn some basics about opening and closing files, I encourage you to check out that article.

Method 1 — AppActivate

Make powerful macros with our free VBA Developer Kit

This is actually pretty neat. If you have trouble understanding or remembering it, our free VBA Developer Kit can help. It’s loaded with VBA shortcuts to help you make your own macros like this one — we’ll send a copy, along with our Big Book of Excel VBA Macros, to your email address below.

Tutorial

Because the variable vPID is stored as a project level Public Variable, its value will be retained for as long as your instance of Excel (or other Microsoft Office application) is open.

If no value is assigned to the variable, a new instance of whatever program you want to open will appear. In this case, notepad.exe was opened.

The magic happens when you run this program a second time. Instead of opening a second notepad window, the previously opened window will activate! The AppActivate statement makes all this happen.

Normally, the AppActivate statement is used to activate an existing application based on its title. For example, if you have an open program called “Calculator,” you can type AppActivate («Calculator») to activate that window. Fortunately, the AppActivate Function can also accept a process ID instead of a title, which makes it far more robust!

Again, the AppActivate example will not work if trying to reactivate a folder you previously opened with explorer.exe. Keep reading for folder-compatible solution.

Method 2 — explorer.exe Folders

Tutorial

Recall in my VBA Shell article, I had some pretty heavy disclaimers about using explorer.exe to open folders. The reason I made those disclaimers is that the Process ID, vPID , for explorer.exe is not retained after your folder opens. Trying to activate the window via the stored vPID will do nothing! No need to give up, though. The above example is the solution.

In the explorer.exe example, the script opens my My Documents folder. Change the path in the strDirectory variable to whatever folder path you want to open.

The macro works by looping through all your open windows. If the path in your Windows Explorer top bar matches the path in your macro, that window will activate. If the macro can’t find the path, it will open it. The next time you run the macro, the previously opened window will activate!

You may wonder why the w.Visible=False and w.Visible=True lines appear back to back. It’s been my experience that without first hiding the window by setting its visibility to False, the window sometimes would not reactivate. Your mileage may vary, so play around and see what you think.

Closing Thoughts

Since I published my VBA Shell article earlier this year, I’ve received several emails asking how to prevent the macros from opening multiple instances of the same application when re-executed. I’m hoping the skills you learned here will help you solve this problem.

This article is another example of how your emails and your comments are an important avenue for great VBA content ideas. Who knows, a question you ask on our [VBA Q&A] platform today may turn into an article tomorrow!

When you’re ready to take your VBA to the next level, subscribe using the form below.

Ready to do more with VBA?
We put together a giant PDF with over 300 pre-built macros and we want you to have it for free. Enter your email address below and we’ll send you a copy along with our VBA Developer Kit, loaded with VBA tips, tricks and shortcuts.

Before we go, I want to let you know we designed a suite of VBA Cheat Sheets to make it easier for you to write better macros. We included over 200 tips and 140 macro examples so they have everything you need to know to become a better VBA programmer.

Источник

This repository has been archived by the owner on Aug 31, 2018. It is now read-only.

Permalink

Cannot retrieve contributors at this time

title keywords f1_keywords ms.prod api_name ms.assetid ms.date

Window.Activate Method (Excel)

vbaxl10.chm356073

vbaxl10.chm356073

excel

Excel.Window.Activate

7e0fdc4e-6399-62a8-f706-1653eb9217a2

06/08/2017

Window.Activate Method (Excel)

Brings the window to the front of the z-order.

Syntax

expression . Activate

expression A variable that represents a Window object.

Return Value

Variant

Remarks

This won’t run any Auto_Activate or Auto_Deactivate macros that might be attached to the workbook (use the RunAutoMacros method to run those macros).

See also

Concepts

Window Object

ThreeWave
Activating Excel From Another Application

This page describes how to activate the Excel application when you are controlling
it via Automation from another application.

ShortFadeBar

If you are doing cross-application programming, such as
working in Word with code to automate Excel, you may find it useful for the
user’s convenience to activate the main Excel window from code running in Word
while Word is the active application. You can try to use the AppActivate
statement, but this requires that you know in advance the caption of the window
you want to activate. Moreover, I have found AppActivate to be somewhat flakey.
Sometimes it works and sometime not (raising an error 5, Invalid Procedure Call).
Moreover it does not always set keyboard focus to the application.

You can work around these problems with AppActivate with a
few simple Windows API functions.

information An API call is a procedure call directly to one of the DLL library files that
make up Windows. While using API functions often allows you to do things that can’t
be done within VBA itself, APIs don’t have the error handling features of VBA code.
If you call an API function with invalid parameters, you will likely crash
Excel and lose all your work. API functions should be used with great caution.

The following code will activate the main Excel window and set keyboard focus to the
ActiveSheet in Excel. Paste the following code into a new code module, and run the macro ActivateExcel.
Note that you must not have any VBA Editors open. If you have a
VBA Editor open, the system will set focus to that Editor window, rather than to
Excel. This problem has largely been fixed in Excel 2007.

For a list of application window classes for most Office applications (versions
2003 and 2007 only) click here.

This code should work for any Office application whose
window class is known. Change the value of C_MAIN_WINDOW_CLASS from
XLMAINto the window class of the other application (e.g.,
OpusApp for Word).

SectionBreak

Option Explicit
Option Compare Text

Private Declare Function BringWindowToTop Lib "user32" ( _
    ByVal HWnd As Long) As Long
Private Declare Function FindWindow Lib "user32" Alias "FindWindowA" ( _
    ByVal lpClassName As String, _
    ByVal lpWindowName As String) As Long
    
Private Declare Function SetFocus Lib "user32" ( _
    ByVal HWnd As Long) As Long

Public Sub ActivateExcel()

    XLHWnd = FindWindow(lpClassName:=C_MAIN_WINDOW_CLASS, _
                    lpWindowName:=vbNullString)
        
        If XLHWnd > 0 Then
        
        Res = BringWindowToTop(HWnd:=XLHWnd)
         
        If Res = 0 Then
            Debug.Print "Error With BringWindowToTop:  " & _
                CStr(Err.LastDllError)
          Else
            
            SetFocus HWnd:=XLHWnd
          End If
    Else
        
        Debug.Print "Can't find Excel"
    End If
End Sub

ShortFadeBar

LastUpdate This page last updated: 25-April-2016.

Step-by-Step Examples to Activate Workbooks with MacrosIn this Excel VBA Tutorial, you learn how to activate workbooks with macros.

This Excel VBA Activate Workbook Tutorial is currently under development. Subscribe to the Power Spreadsheets Newsletter to get future updates to this Excel VBA Tutorial.

Use the following Table of Contents to navigate to the Section you’re interested in.

VBA Code to Activate This Workbook

To activate this workbook, use the following statement in the applicable procedure.

Process to Activate This Workbook with VBA

  1. Refer to this workbook (the workbook where the macro is stored).
  2. Activate the workbook.

Main VBA Constructs Used to Activate This Workbook

(1) Application.ThisWorkbook property.

Returns a Workbook object representing the workbook where the macro is stored (the workbook where the macro is running).

(2) Workbook object.

Represents an Excel workbook.

(3) Workbook.Activate method.

Activates the (first) window associated with a workbook.

Macro Example to Activate This Workbook

The macro below does the following:

  1. Activate this workbook (the workbook where the macro is stored).
  2. Maximize the active window.
Sub ActivateThisWorkbook()
    'Source: https://powerspreadsheets.com/
    'For further information: https://powerspreadsheets.com/excel-vba-activate-workbook/
    
    'This procedure:
        '(1) Activates this workbook (the workbook where the macro is stored)
        '(2) Maximizes the active window
    
    'Activate this workbook
    ThisWorkbook.Activate
    
    'Maximize the active window
    ActiveWindow.WindowState = xlMaximized

End Sub

Effects of Executing Macro Example to Activate This Workbook

The image below illustrates the effects of using the macro example. In this example:

  • 2 workbooks (“Excel VBA Activate Workbook” and “Book1”) are open.
  • The “Book1” workbook is the active workbook.
  • The macro example is stored in the “Excel VBA Activate Workbook” workbook.

When the macro is executed, Excel:

  • Activates this workbook (“Excel VBA Activate Workbook”; the workbook where the macro example is stored); and
  • Maximizes the active window.
Example: Activate this workbook with VBA macros

Excel VBA Activate Workbook by Filename

VBA Code to Activate Workbook by Filename

To activate a workbook by filename, use the following structure/template in the applicable statement.

Workbooks("Filename").Activate

Process to Activate Workbook by Filename with VBA

  1. Refer to the workbook to activate by filename.
  2. Activate the applicable workbook.

Main VBA Constructs Used to Activate Workbook by Filename

(1) Application.Workbooks property.

Returns a Workbooks collection representing all open workbooks.

(2) Workbooks object.

Represents all open workbooks.

(3) Workbooks.Item property.

Returns a specific Workbook object from the applicable Workbooks collection.

(4) Workbook object.

Represents an Excel workbook.

(5) Workbook.Activate method.

Activates the (first) window associated with a workbook.

Cues to Activate Workbook by Filename with VBA

  • Consider whether you must wrap the workbook filename in double quotes and parentheses ((“Filename”)).
  • As a general rule: Include the complete filename, including file extension (for ex., “Filename.xlsm”), of a previously saved workbook.

Macro Example to Activate Workbook by Filename

The macro below does the following:

  1. Activate the workbook with filename “Excel VBA Activate Workbook.xlsm”.
  2. Maximize the active window.
Sub ActivateWorkbookByFilename()
    'Source: https://powerspreadsheets.com/
    'For further information: https://powerspreadsheets.com/excel-vba-activate-workbook/
    
    'This procedure:
        '(1) Activates the workbook with filename "Excel VBA Activate Workbook.xlsm"
        '(2) Maximizes the active window
    
    'Activate the workbook with filename "Excel VBA Activate Workbook.xlsm"
    Workbooks("Excel VBA Activate Workbook.xlsm").Activate
    
    'Maximize the active window
    ActiveWindow.WindowState = xlMaximized

End Sub

Effects of Executing Macro Example to Activate Workbook by Filename

The image below illustrates the effects of using the macro example. In this example:

  • 2 workbooks (“Excel VBA Activate Workbook.xlsm” and “Book1”) are open.
  • The “Book1” workbook is the active workbook.

When the macro is executed, Excel:

  • Activates the workbook with filename “Excel VBA Activate Workbook.xlsm”; and
  • Maximizes the active window.
Example: Activate workbook by filename with VBA macros

Excel VBA Activate Workbook with Partial Filename (with Left, Mid, or Right Functions)

VBA Code to Activate Workbook with Partial Filename (with Left, Mid, or Right Functions)

To activate a workbook with partial filename (with the Left, Mid, or Right functions), use the following structure/template in the applicable procedure.

VariableDeclarationStatement iWorkbook As Workbook
For Each iWorkbook In Application.Workbooks
    If VbaBuiltInTextFunction(TextFunctionArgumentsIncludingWorkbookName) = "PartialWorkbookFilename" Then
        iWorkbook.Activate
    End If
Next iWorkbook

Process to Activate Workbook with Partial Filename (with Left, Mid, or Right Functions)

  1. Declare iteration object variable (usually of the Workbook object data type).
  2. Loop through all open workbooks.
  3. Test whether the applicable part (for example, the beginning or end) of the name of the workbook (the loop is currently iterating through) matches the (known) partial filename (of the workbook to activate).
  4. If the condition is met (the applicable part of the name of the applicable workbook matches the partial filename of the workbook to activate), activate the workbook (the loop is currently iterating through).

Main VBA Constructs Used to Activate Workbook with Partial Filename (with Left, Mid, or Right Functions)

(1) Variable declaration statement.

One of the following 4 statements:

  • Dim: Declares variables and allocates storage space.
  • Private:
    • Used at the module level.
    • Declares module-level variables and allocates storage space.
  • Public:
    • Used at the module level.
    • Declares global variables and allocates storage space.
  • Static: Declares static variables and allocates storage space.

(2) Workbook object.

Represents an Excel workbook.

(3) For Each… Next statement.

Repeats a set of statements for each element in an array or collection.

(4) Application.Workbooks property.

Returns a Workbooks collection representing all open workbooks.

(5) Workbooks object.

Represents all open workbooks.

(6) Object variable.

A named storage location containing data (a reference to an object) that can be modified during procedure execution.

(7) If… Then… Else statement.

Conditionally executes a set of statements, depending on the value returned by a logical expression.

(8) VBA built-in text function.

One (or more) of the following VBA built-in text functions:

  • Left: Returns a string containing a specific number of characters from the start (left side) of a string.
  • Mid: Returns a string containing a specific number of characters from the middle (starting at a specific position) of a string.
  • Right: Returns a string containing a specific number of characters from the end (right side) of a string.
  • InStr: Returns the position of the first occurrence of one string inside another string.

(9) String.

A sequence of contiguous characters.

(10) Workbook.Activate method.

Activates the (first) window associated with a workbook.

Cues to Activate Workbook with Partial Filename (with Left, Mid, or Right Functions) with VBA

  • Consider explicitly declaring:
    • The iteration object variable.
    • The data type (usually Workbook object) of the iteration object variable.
  • As a general rule, declare the iteration object variable:
    • Using the Dim statement; and
    • As of the Workbook object data type.
  • If the scope of the iteration object variable is module-level or global, follow the applicable rules for (module-level or global) variable declaration.
  • Depending on the case you deal with, you may need to work with different versions of the If… Then… Else statement. Consider the following 4 basic versions of the If… Then… Else statement:
    • If… Then. This is the version I use in the structure/template above.
    • If… Then… Else.
    • If… Then… ElseIf.
    • If… Then… ElseIf… Else.
  • The appropriate VBA built-in text function you work with depends on the case you deal with (for example, the structure and position of the known partial filename).
  • As a general rule:
    • The (main) string you use as one of the arguments of the VBA built-in text function (the string from which you extract characters) is the name of the applicable workbook (the For Each… Next statement is currently iterating through).
    • Work with the Workbook.Name property to obtain the name of the applicable workbook. The Workbook.Name property returns a workbook’s name.
  • When specifying the (known) partial filename, consider whether you must wrap this partial filename in double quotes (“PartialWorkbookFilename”).

Macro Example to Activate Workbook with Partial Filename (with Left, Mid, or Right Functions)

The macro below does the following:

  1. Declare an object variable (iWorkbook) of the Workbook object data type.
  2. Loop through all open workbooks.
  3. Test whether the first/leftmost 9 letters of the name of the workbook (the loop is currently iterating through) spell “Excel VBA”.
  4. If the condition is met (the first/leftmost 9 letters of the name of the applicable workbook spell “Excel VBA”), activate the workbook (the loop is currently iterating through).
Sub ActivateWorkbookPartialFilenameLeftMidRight()
    'Source: https://powerspreadsheets.com/
    'For further information: https://powerspreadsheets.com/excel-vba-activate-workbook/
    
    'Declare iteration object variable
    Dim iWorkbook As Workbook
    
    'Loop through all open workbooks
    For Each iWorkbook In Application.Workbooks
        
        'Do the following:
            '(1) Test whether the first/leftmost 9 letters of the name of the workbook (the loop is currently iterating through) spell "Excel VBA"
            '(2) If the condition is met, activate the workbook (the loop is currently iterating through)
        If Left(iWorkbook.Name, 9) = "Excel VBA" Then iWorkbook.Activate
    
    Next iWorkbook
    
End Sub

Effects of Executing Macro Example to Activate Workbook with Partial Filename (with Left, Mid, or Right Functions)

The image below illustrates the effects of using the macro example. In this example:

  • 10 workbooks (“Excel VBA Activate Workbook.xlsm”, and “Book1” through “Book9”) are open.
  • The “Book1” workbook is the active workbook.

When the macro is executed, Excel activates the workbook whose filename (Excel VBA Activate Workbook.xlsm) contains the (known) partial filename (Excel VBA).

Example: Activate Workbook with Partial Filename (with Left, Mid, or Right Functions) with VBA macros

Excel VBA Activate Workbook with Partial Filename (with InStr Function)

VBA Code to Activate Workbook with Partial Filename (with InStr Function)

To activate a workbook with partial filename (with the InStr function), use the following structure/template in the applicable procedure.

VariableDeclarationStatement iWorkbook As Workbook
For Each iWorkbook In Application.Workbooks
    If InStr(1, iWorkbook.Name, "PartialWorkbookFilename", StringCompareMethodConstant) > 0 Then
        iWorkbook.Activate
    End If
Next iWorkbook

Process to Activate Workbook with Partial Filename (with InStr Function)

  1. Declare iteration object variable (usually of the Workbook object data type).
  2. Loop through all open workbooks.
  3. Test whether the name of the workbook (the loop is currently iterating through) contains the (known) partial filename (of the workbook to activate).
  4. If the condition is met (the name of the applicable workbook contains the partial filename of the workbook to activate), activate the workbook (the loop is currently iterating through).

Main VBA Constructs Used to Activate Workbook with Partial Filename (with InStr Function)

(1) Variable declaration statement.

One of the following 4 statements:

  • Dim: Declares variables and allocates storage space.
  • Private:
    • Used at the module level.
    • Declares module-level variables and allocates storage space.
  • Public:
    • Used at the module level.
    • Declares global variables and allocates storage space.
  • Static: Declares static variables and allocates storage space.

(2) Workbook object.

Represents an Excel workbook.

(3) For Each… Next statement.

Repeats a set of statements for each element in an array or collection.

(4) Application.Workbooks property.

Returns a Workbooks collection representing all open workbooks.

(5) Workbooks object.

Represents all open workbooks.

(6) Object variable.

A named storage location containing data (a reference to an object) that can be modified during procedure execution.

(7) If… Then… Else statement.

Conditionally executes a set of statements, depending on the value returned by a logical expression.

(8) InStr function.

Returns the position of the first occurrence of one string inside another string.

Accepts the following 4 arguments:

  • start:
    • Optional argument.
    • The starting position for the search.
    • If omitted, the search begins at the first character.
  • string1:
    • Required argument.
    • The string you search in.
  • string2:
    • Required argument.
    • The string you search for.
  • compare:
    • Optional argument.
    • The string comparison method.
    • If omitted, the module’s Option Compare setting applies.

(9) Workbook.Name property.

Returns a workbook’s name.

(10) String.

A sequence of contiguous characters.

(11) Greater than operator (>).

Compares 2 expressions and returns True, False, or Null as follows:

  • True: If Expression1 > Expression2.
  • False: If Expression1 <= Expression2.
  • Null: If (either) Expression1 or Expression2 are Null.

(12) Workbook.Activate method.

Activates the (first) window associated with a workbook.

Cues to Activate Workbook with Partial Filename (with InStr Function) with VBA

  • Consider explicitly declaring:
    • The iteration object variable.
    • The data type (usually Workbook object) of the iteration object variable.
  • As a general rule, declare the iteration object variable:
    • Using the Dim statement; and
    • As of the Workbook object data type.
  • If the scope of the iteration object variable is module-level or global, follow the applicable rules for (module-level or global) variable declaration.
  • Depending on the case you deal with, you may need to work with different versions of the If… Then… Else statement. Consider the following 4 basic versions of the If… Then… Else statement:
    • If… Then. This is the version I use in the structure/template above.
    • If… Then… Else.
    • If… Then… ElseIf.
    • If… Then… ElseIf… Else.
  • As a general rule, set the arguments of the InStr function as follows:
    • start: 1.
    • string1: The name of the workbook the loop is currently iterating through, as returned by the Workbook.Name property.
    • string2: The (known) partial filename.
    • compare: vbBinaryCompare. vbBinaryCompare (usually) results in a case sensitive comparison.
  • When specifying the (known) partial filename (as string2 argument of the InStr function), consider whether you must wrap this partial filename in double quotes (“PartialWorkbookFilename”).

Macro Example to Activate Workbook with Partial Filename (with InStr Function)

The macro below does the following:

  1. Declare an object variable (iWorkbook) of the Workbook object data type.
  2. Loop through all open workbooks.
  3. Test whether the name of the workbook (the loop is currently iterating through) contains “Excel VBA”.
  4. If the condition is met (the name of the applicable workbook contains “Excel VBA”), activate the workbook (the loop is currently iterating through).
Sub ActivateWorkbookPartialFilenameInStr()
    'Source: https://powerspreadsheets.com/
    'For further information: https://powerspreadsheets.com/excel-vba-activate-workbook/
    
    'Declare iteration object variable
    Dim iWorkbook As Workbook
    
    'Loop through all open workbooks
    For Each iWorkbook In Application.Workbooks
        
        'Do the following:
            '(1) Test whether the name of the workbook (the loop is currently iterating through) contains "Excel VBA"
            '(2) If the condition is met, activate the workbook (the loop is currently iterating through)
        If InStr(1, iWorkbook.Name, "Excel VBA", vbBinaryCompare) > 0 Then iWorkbook.Activate
    
    Next iWorkbook

End Sub

Effects of Executing Macro Example to Activate Workbook with Partial Filename (with InStr Function)

The image below illustrates the effects of using the macro example. In this example:

  • 10 workbooks (“Excel VBA Activate Workbook.xlsm”, and “Book1” through “Book9”) are open.
  • The “Book1” workbook is the active workbook.

When the macro is executed, Excel activates the workbook whose filename (Excel VBA Activate Workbook.xlsm) contains the (known) partial filename (Excel VBA).

Example: Activate Workbook with Partial Filename (with InStr Function) with VBA macros

Excel VBA Activate Workbook Using Wildcard

VBA Code to Activate Workbook Using Wildcard

To activate a workbook using a wildcard, use the following structure/template in the applicable procedure.

VariableDeclarationStatement Dim iWorkbook As Workbook
For Each iWorkbook In Application.Workbooks
    If iWorkbook.Name Like "WorkbookNameUsingWildcard" Then
        iWorkbook.Activate
    End If
Next iWorkbook

Process to Activate Workbook Using Wildcard

  1. Declare iteration object variable (usually of the Workbook object data type).
  2. Loop through all open workbooks.
  3. Test whether the name of the workbook (the loop is currently iterating through) is like the (known) filename (of the workbook to activate). Use wildcards (as necessary) to specify the filename of the workbook to activate.
  4. If the condition is met (the name of the applicable workbook is like the filename -including any wildcards- of the workbook to activate), activate the workbook (the loop is currently iterating through).

Main VBA Constructs Used to Activate Workbook Using Wildcard

(1) Variable declaration statement.

One of the following 4 statements:

  • Dim: Declares variables and allocates storage space.
  • Private:
    • Used at the module level.
    • Declares module-level variables and allocates storage space.
  • Public:
    • Used at the module level.
    • Declares global variables and allocates storage space.
  • Static: Declares static variables and allocates storage space.

(2) Workbook object.

Represents an Excel workbook.

(3) For Each… Next statement.

Repeats a set of statements for each element in an array or collection.

(4) Application.Workbooks property.

Returns a Workbooks collection representing all open workbooks.

(5) Workbooks object.

Represents all open workbooks.

(6) Object variable.

A named storage location containing data (a reference to an object) that can be modified during procedure execution.

(7) If… Then… Else statement.

Conditionally executes a set of statements, depending on the value returned by a logical expression.

(8) Workbook.Name property.

Returns a workbook’s name.

(9) Like operator.

Compares a string against a pattern and returns True, False, or Null as follows:

  • True: If the string matches the pattern.
  • False: If the string doesn’t match the pattern.
  • Null: If (either) the string or the pattern are Null.

You can combine the following elements when specifying the pattern:

  • Wildcard characters.
  • Character lists.
  • Character ranges.

(10) String.

A sequence of contiguous characters.

(11) Workbook.Activate method.

Activates the (first) window associated with a workbook.

Cues to Activate Workbook Using Wildcard with VBA

  • Consider explicitly declaring:
    • The iteration object variable.
    • The data type (usually Workbook object) of the iteration object variable.
  • As a general rule, declare the iteration object variable:
    • Using the Dim statement; and
    • As of the Workbook object data type.
  • If the scope of the iteration object variable is module-level or global, follow the applicable rules for (module-level or global) variable declaration.
  • Depending on the case you deal with, you may need to work with different versions of the If… Then… Else statement. Consider the following 4 basic versions of the If… Then… Else statement:
    • If… Then. This is the version I use in the structure/template above.
    • If… Then… Else.
    • If… Then… ElseIf.
    • If… Then… ElseIf… Else.
  • Use the Like operator to compare the string returned by the Workbook.Name property (the name of the workbook the loop is currently iterating through) against a string with the filename (including any wildcards) of the workbook to activate.
  • Use the following wildcards when specifying the pattern the Like operator works with:
    • ?: Represents any single character.
    • *: Represents any sequence of 0 or more characters.
  • When specifying the pattern the Like operator works with (the filename -including any wildcards- of the workbook to activate), consider whether you must wrap this partial filename in double quotes (“WorkbookNameUsingWildcard”).

Macro Example to Activate Workbook Using Wildcard

The macro below does the following:

  1. Declare an object variable (iWorkbook) of the Workbook object data type.
  2. Loop through all open workbooks.
  3. Test whether the name of the workbook (the loop is currently iterating through) has the following structure:
    1. Starts with “Excel VBA”;
    2. Followed by any sequence of characters; and
    3. Ends with the “.xlsm” file extension.
  4. If the condition is met (the name of the applicable workbook is like the specified filename, including the * wildcard), activate the workbook (the loop is currently iterating through).
Sub ActivateWorkbookUsingWildcard()
    'Source: https://powerspreadsheets.com/
    'For further information: https://powerspreadsheets.com/excel-vba-activate-workbook/
    
    'Declare iteration object variable
    Dim iWorkbook As Workbook
    
    'Loop through all open workbooks
    For Each iWorkbook In Application.Workbooks
        
        'Do the following:
            '(1) Test whether the name of the workbook (the loop is currently iterating through) has the following structure:
                '(1) Starts with "Excel VBA"
                '(2) Followed by any sequence of characters
                '(3) Ends with the ".xlsm" file extension
            '(2) If the condition is met, activate the workbook (the loop is currently iterating through)
        If iWorkbook.Name Like "Excel VBA*.xlsm" Then iWorkbook.Activate
    
    Next iWorkbook
    
End Sub

Effects of Executing Macro Example to Activate Workbook Using Wildcard

The image below illustrates the effects of using the macro example. In this example:

  • 10 workbooks (“Excel VBA Activate Workbook.xlsm”, and “Book1” through “Book9”) are open.
  • The “Book1” workbook is the active workbook.

When the macro is executed, Excel activates the workbook whose filename (Excel VBA Activate Workbook.xlsm) has the following structure:

  1. Starts with “Excel VBA”;
  2. Followed by any sequence of characters; and
  3. Ends with the “.xlsm” file extension.

Example: Activate workbook using wildcard with VBA macros

Excel VBA Activate Workbook and Worksheet

VBA Code to Activate Workbook and Worksheet

To activate a workbook and a worksheet, use the following structure/template in the applicable statement.

WorkbookObjectReference.WorksheetObjectReference.Activate

Process to Activate Workbook and Worksheet with VBA

  1. Refer to the workbook and worksheet to activate.
  2. Activate the applicable worksheet.

Main VBA Constructs Used to Activate Workbook and Worksheet

(1) Workbook object.

Represents an Excel workbook.

(2) Workbook.Worksheets property.

Returns a Sheets collection representing all worksheets in the applicable workbook.

(3) Worksheets object.

Represents all worksheets in the applicable workbook.

(4) Worksheets.Item property.

Returns a specific Worksheet object from the applicable Worksheets collection.

(5) Worksheet object.

Represents a worksheet.

(6) Worksheet.Activate method.

Activates the applicable worksheet.

Cues to Activate Workbook and Worksheet with VBA

  • Work with (among others) one of the following VBA constructs (or groups of constructs) to return a Workbook object:
    • Application.Workbooks property, Workbooks object, and Workbooks.Item property.
    • Application.ThisWorkbook property.
  • As a general rule, identify the applicable Worksheet object (inside the Worksheets collection) using one of the following:
    • An index number. The index number:
      • Represents the position of the Worksheet object in the Worksheets collection.
      • Is:
        • Wrapped in parentheses ((IndexNumber)).
        • Included after the reference to the Worksheets collection (Worksheets(IndexNumber)).
    • The Worksheet object’s name (Worksheet.Name property). The name is:
      • Wrapped in:
        • Double quotes (“WorksheetName”); and
        • Parentheses ((“WorksheetName”)).
      • Included after the reference to the Worksheets collection (Worksheets(“WorksheetName”)).
  • You can (also) use a Worksheet object’s CodeName property (Worksheet.CodeName property) to refer to the applicable worksheet.

Macro Example to Activate Workbook and Worksheet

The macro below does the following:

  1. Activate:
    1. The “Excel VBA Activate Workbook.xlsm” workbook; and
    2. The “Activate Workbook and Worksheet” worksheet.
  2. Maximize the active window.
Sub ActivateWorkbookAndWorksheet()
    'Source: https://powerspreadsheets.com/
    'For further information: https://powerspreadsheets.com/excel-vba-activate-workbook/
    
    'This procedure:
        '(1) Activates the "Activate Workbook and Worksheet" worksheet in the "Excel VBA Activate Workbook.xlsm" workbook
        '(2) Maximizes the active window
    
    'Activate the "Activate Workbook and Worksheet" worksheet in the "Excel VBA Activate Workbook.xlsm" workbook
    Workbooks("Excel VBA Activate Workbook.xlsm").Worksheets("Activate Workbook and Worksheet").Activate
    
    'Maximize the active window
    ActiveWindow.WindowState = xlMaximized

End Sub

Effects of Executing Macro Example to Activate Workbook and Worksheet

The image below illustrates the effects of using the macro example. In this example:

  • 2 workbooks (“Excel VBA Activate Workbook.xlsm” and “Book1”) are open.
  • The “Book1” workbook is the active workbook.
  • The “Sheet1” worksheet is the active worksheet in both (“Excel VBA Activate Workbook.xlsm” and “Book1”) workbooks.

When the macro is executed, Excel:

  • Activates:
    • The “Excel VBA Activate Workbook.xlsm” workbook; and
    • The “Activate Workbook and Worksheet” worksheet.
  • Maximizes the active window.
Example: Activate workbook and worksheet with VBA macros

Excel VBA Activate Workbook and Chart Sheet

VBA Code to Activate Workbook and Chart Sheet

To activate a workbook and a chart sheet, use the following structure/template in the applicable statement.

WorkbookObjectReference.ChartObjectReference.Activate

Process to Activate Workbook and Chart Sheet with VBA

  1. Refer to the workbook and chart sheet to activate.
  2. Activate the applicable chart sheet.

Main VBA Constructs Used to Activate Workbook and Chart Sheet

(1) Workbook object.

Represents an Excel workbook.

(2) Workbook.Charts property.

Returns a Sheets collection representing all chart sheets in the applicable workbook.

(3) Charts object.

Represents all chart sheets in the applicable workbook.

(4) Charts.Item property.

Returns a specific Chart object from the applicable Charts collection.

(5) Chart object.

Represents a chart in a workbook. The chart can be either of the following:

  • A chart sheet.
  • An embedded chart (not the subject of this Section).

(6) Chart.Activate method.

Activates the applicable chart.

Cues to Activate Workbook and Chart Sheet with VBA

  • Work with (among others) one of the following VBA constructs (or groups of constructs) to return a Workbook object:
    • Application.Workbooks property, Workbooks object, and Workbooks.Item property.
    • Application.ThisWorkbook property.
  • As a general rule, identify the applicable Chart object (inside the Charts collection) using one of the following:
    • An index number. The index number:
      • Represents the position of the Chart object in the Charts collection.
      • Is:
        • Wrapped in parentheses ((IndexNumber)).
        • Included after the reference to the Charts collection (Charts(IndexNumber)).
    • The Chart object’s name (Chart.Name property). The name is:
      • Wrapped in:
        • Double quotes (“ChartSheetName”); and
        • Parentheses ((“ChartSheetName”)).
      • Included after the reference to the Charts collection (Charts(“ChartSheetName”)).
  • You can (also) use a Chart object’s CodeName property (Chart.CodeName property) to refer to the applicable chart sheet.

Macro Example to Activate Workbook and Chart Sheet

The macro below does the following:

  1. Activate:
    1. The “Excel VBA Activate Workbook.xlsm” workbook; and
    2. The “Activate Workbook Chart Sheet” chart sheet.
  2. Maximize the active window.
Sub ActivateWorkbookAndChartSheet()
    'Source: https://powerspreadsheets.com/
    'For further information: https://powerspreadsheets.com/excel-vba-activate-workbook/
    
    'This procedure:
        '(1) Activates the "Activate Workbook Chart Sheet" chart sheet in the "Excel VBA Activate Workbook.xlsm" workbook
        '(2) Maximizes the active window
    
    'Activate the "Activate Workbook Chart Sheet" chart sheet in the "Excel VBA Activate Workbook.xlsm" workbook
    Workbooks("Excel VBA Activate Workbook.xlsm").Charts("Activate Workbook Chart Sheet").Activate
    
    'Maximize the active window
    ActiveWindow.WindowState = xlMaximized
    
End Sub

Effects of Executing Macro Example to Activate Workbook and Chart Sheet

The image below illustrates the effects of using the macro example. In this example:

  • 2 workbooks (“Excel VBA Activate Workbook.xlsm” and “Book1”) are open.
  • The “Book1” workbook is the active workbook.
  • The “Sheet1” worksheet is the active sheet in both (“Excel VBA Activate Workbook.xlsm” and “Book1”) workbooks.

When the macro is executed, Excel:

  • Activates:
    • The “Excel VBA Activate Workbook.xlsm” workbook; and
    • The “Activate Workbook Chart Sheet” chart sheet.
  • Maximizes the active window.

Example: Activate workbook and chart sheet with VBA macros

Excel VBA Activate Workbook with Variable Name

VBA Code to Activate Workbook with Variable Name

To activate a workbook with variable name (where the workbook filename is held by a variable), use the following structure/template in the applicable procedure.

VariableDeclarationStatement WorkbookFilenameVariable As String
WorkbookFilenameVariable = WorkbookFilenameString
Workbooks(WorkbookFilenameVariable).Activate

Process to Activate Workbook with Variable Name

  1. Declare variable (usually of the String data type) to represent workbook filename.
  2. Assign workbook filename to variable.
  3. Refer to the workbook to activate by using the applicable variable name (representing the workbook filename).
  4. Activate the applicable workbook.

Main VBA Constructs Used to Activate Workbook with Variable Name

(1) Variable declaration statement.

One of the following 4 statements:

  • Dim: Declares variables and allocates storage space.
  • Private:
    • Used at the module level.
    • Declares module-level variables and allocates storage space.
  • Public:
    • Used at the module level.
    • Declares global variables and allocates storage space.
  • Static: Declares static variables and allocates storage space.

(2) String data type.

Holds textual data (a sequence of characters representing the characters themselves).

(3) Assignment operator (=).

Assigns a value to a variable or property.

(4) Application.Workbooks property.

Returns a Workbooks collection representing all open workbooks.

(5) Workbooks object.

Represents all open workbooks.

(6) Workbooks.Item property.

Returns a specific Workbook object from the applicable Workbooks collection.

(7) Workbook object.

Represents an Excel workbook.

(8) Variable.

A named storage location containing data that can be modified during procedure execution.

(9) Workbook.Activate method.

Activates the (first) window associated with a workbook.

Cues to Activate Workbook with Variable Name with VBA

  • Consider explicitly declaring:
    • The variable representing the workbook filename.
    • The data type (usually String) of the variable representing the workbook filename.
  • As a general rule, declare the variable representing the workbook filename:
    • Using the Dim statement; and
    • As of the String data type.
  • If the scope of the variable representing the workbook filename is module-level or global, follow the applicable rules for (module-level or global) variable declaration.
  • When assigning the workbook filename to the variable representing the workbook filename:
    • Consider whether you must wrap the workbook filename in double quotes and parentheses ((“Filename”)).
    • As a general rule:
      • Include the complete filename, including file extension (for ex., “Filename.xlsm”), of a previously saved workbook.
      • Do not include the file path.

Macro Example to Activate Workbook with Variable Name

The macro below does the following:

  1. Declare a variable (WorkbookFilename) of the String data type.
  2. Assign a string (Excel VBA Activate Workbook.xlsm) to the WorkbookFilename variable.
  3. Activate the workbook whose filename is represented by the WorkbookFilename variable.
  4. Maximize the active window.
Sub ActivateWorkbookWithVariableName()
    'Source: https://powerspreadsheets.com/
    'For further information: https://powerspreadsheets.com/excel-vba-activate-workbook/
    
    'This procedure:
        '(1) Declares a variable (WorkbookFilename) of the String data type
        '(2) Assigns a string (Excel VBA Activate Workbook.xlsm) to the WorkbookFilename variable
        '(3) Activates the workbook whose filename is represented by the WorkbookFilename variable
        '(4) Maximizes the active window
    
    'Declare variable to represent workbook filename
    Dim WorkbookFilename As String
    
    'Assign workbook filename to variable
    WorkbookFilename = "Excel VBA Activate Workbook.xlsm"
    
    'Activate the workbook whose filename is represented by the WorkbookFilename variable
    Workbooks(WorkbookFilename).Activate
    
    'Maximize the active window
    ActiveWindow.WindowState = xlMaximized

End Sub

Effects of Executing Macro Example to Activate Workbook with Variable Name

The image below illustrates the effects of using the macro example. In this example:

  • 2 workbooks (“Excel VBA Activate Workbook.xlsm” and “Book1”) are open.
  • The “Book1” workbook is the active workbook.

When the macro is executed, Excel:

  • Activates the workbook whose filename (Excel VBA Activate Workbook.xlsm) is held by a variable (WorkbookFilename); and
  • Maximizes the active window.
Example: Activate Workbook with Variable Name with VBA macros

Excel VBA Activate Workbook with Object Variable Name

VBA Code to Activate Workbook with Object Variable Name

To activate a workbook with object variable name (where the Workbook object is represented by an object variable), use the following structure/template in the applicable procedure.

VariableDeclarationStatement WorkbookObjectVariable As Workbook
Set WorkbookObjectVariable = WorkbookObjectReference
WorkbookObjectVariable.Activate

Process to Activate Workbook with Object Variable Name

  1. Declare object variable (usually of the Workbook object data type) to represent workbook.
  2. Assign Workbook object reference to object variable.
  3. Refer to the workbook to activate by using the applicable object variable name (representing the workbook).
  4. Activate the applicable workbook.

Main VBA Constructs Used to Activate Workbook with Object Variable Name

(1) Variable declaration statement.

One of the following 4 statements:

  • Dim: Declares variables and allocates storage space.
  • Private:
    • Used at the module level.
    • Declares module-level variables and allocates storage space.
  • Public:
    • Used at the module level.
    • Declares global variables and allocates storage space.
  • Static: Declares static variables and allocates storage space.

(2) Workbook object.

Represents an Excel workbook.

(3) Set statement.

Assigns an object reference to a variable or property.

(4) Application.Workbooks property.

Returns a Workbooks collection representing all open workbooks.

(5) Workbooks object.

Represents all open workbooks.

(6) Workbooks.Item property.

Returns a specific Workbook object from the applicable Workbooks collection.

(7) Object Variable.

A named storage location containing data (a reference to an object) that can be modified during procedure execution.

(8) Workbook.Activate method.

Activates the (first) window associated with a workbook.

Cues to Activate Workbook with Object Variable Name with VBA

  • Consider explicitly declaring:
    • The object variable representing the workbook.
    • The data type (usually Workbook object) of the object variable representing the workbook.
  • As a general rule, declare the object variable representing the workbook:
    • Using the Dim statement; and
    • As of the Workbook object data type.
  • If the scope of the object variable representing the workbook is module-level or global, follow the applicable rules for (module-level or global) variable declaration.

Macro Example to Activate Workbook with Object Variable Name

The macro below does the following:

  1. Declare an object variable (WorkbookObjectVariable) of the Workbook object data type.
  2. Assign a Workbook object reference (Excel VBA Activate Workbook.xlsm) to the WorkbookObjectVariable object variable.
  3. Activate the workbook represented by the WorkbookObjectVariable object variable.
  4. Maximize the active window.
Sub ActivateWorkbookWithObjectVariableName()
    'Source: https://powerspreadsheets.com/
    'For further information: https://powerspreadsheets.com/excel-vba-activate-workbook/
    
    'This procedure:
        '(1) Declares an object variable (WorkbookObjectVariable) of the Workbook object data type
        '(2) Assigns a Workbook object reference (to the "Excel VBA Activate Workbook.xlsm" workbook) to the WorkbookObjectVariable object variable
        '(3) Activates the workbook represented by the WorkbookObjectVariable object variable
        '(4) Maximizes the active window
    
    'Declare object variable to represent workbook
    Dim WorkbookObjectVariable As Workbook
    
    'Assign Workbook object reference to object variable
    Set WorkbookObjectVariable = Workbooks("Excel VBA Activate Workbook.xlsm")
    
    'Activate workbook represented by the WorkbookObjectVariable object variable
    WorkbookObjectVariable.Activate
    
    'Maximize the active window
    ActiveWindow.WindowState = xlMaximized

End Sub

Effects of Executing Macro Example to Activate Workbook with Object Variable Name

The image below illustrates the effects of using the macro example. In this example:

  • 2 workbooks (“Excel VBA Activate Workbook.xlsm” and “Book1”) are open.
  • The “Book1” workbook is the active workbook.

When the macro is executed, Excel:

  • Activates the workbook whose reference (Excel VBA Activate Workbook.xlsm) is held by an object variable (WorkbookObjectVariable); and
  • Maximizes the active window.
Example: Activate Workbook with Object Variable Name with VBA macros

Excel VBA Open and Activate Workbook

VBA Code to Open and Activate Workbook

To open and activate a workbook, use the following structure/template in the applicable statement.

Workbooks.Open Filename:="PathAndFilename"

Process to Open and Activate Workbook with VBA

  1. Open the workbook with the Workbooks.Open method.

Main VBA Constructs Used to Open and Activate Workbook

(1) Workbooks.Open method.

Opens a workbook.

(2) Filename parameter.

The:

  • First parameter of the Workbooks.Open method.
  • Filename of the workbook to open.

Cues to Open and Activate Workbook with VBA

  • When you open a workbook with the Workbooks.Open method, the opened workbook becomes the active workbook.
  • Consider whether you must wrap the workbook path and filename in double quotes (“PathAndFilename”).
  • As a general rule:
    • Include the full path and filename (including file extension).
    • If the workbook is stored in the default file folder (where Excel currently saves files by default), you can exclude the workbook’s path (use only the filename, including file extension).

Macro Example to Open and Activate Workbook

The macro below opens (and activates) the workbook with filename “Excel VBA Open and Activate Workbook.xlsx” stored in the Desktop folder.

Sub OpenAndActivateWorkbook()
    'Source: https://powerspreadsheets.com/
    'For further information: https://powerspreadsheets.com/excel-vba-activate-workbook/
    
    'Open the workbook with filename "Excel VBA Open and Activate Workbook.xlsx" stored in the Desktop folder. The opened workbook becomes the active workbook
    Workbooks.Open Filename:="C:UsersPowerSpreadsheetsDesktopExcel VBA Open and Activate Workbook.xlsx"
    
End Sub

Effects of Executing Macro Example to Open and Activate Workbook

The image below illustrates the effects of using the macro example.

In this example (only) 1 workbook (“Excel VBA Activate Workbook”) is open. This is (also) the active workbook.

When the macro is executed, Excel opens and activates the workbook with filename “Excel VBA Open and Activate Workbook.xlsx” stored in the Desktop folder.

Example: Open and Activate Workbook with VBA macros

Как сделать книгу активной, зная имя книги?

​Смотрите также​​P. S. На​ стопорится из-за того​ создать Новую книгу​

​Selection.Insert Shift:=xlToRight​​ Подскажите пжл, как​​ l&, r As​​ Dim xlsWb As​ xlsApp As Object​

​ ему имя «Новый​​ тот не сработал​

​ и т.п. При​​ взяли имя активной​ файлов, к которому​

​ момент, когда Вы​​: Обратиться к рабочей​ расширения файлов, то​PuLbKa​ ум пришло только​ что не переключается​ для помещения туда​Set nb =​ исправить.​

​ Range Set xlsApp​​ Excel.Workbook Dim xlsSh​ Dim xlsWb As​

​ лист» Dim oRange​​ правильно…​ этом ввод пользователя​
​ книги и продолжайте​ после этого будет​ точно знаете, что​​ книге можно по​​ так​
​: Как сделать книгу​ создание буферной папки.​​Guest​​ результатов, переключиться на​ Workbooks.Add​Selection.Find(What:=»», After:=ActiveCell, LookAt:=xlPart).Select​ = GetObject(, «Excel.Application»)​ As Excel.Worksheet Dim​
​ Object Dim xlsSh​
​ As Range ‘Находим​Если честно я​ блокируется, а указатель​ свой макрос.​

​ применен макрос. Имена​​ нужная книга активна,​ имени или по​При открытой книге​ активной зная имя​JayBhagavan​: Это были эксперименты​ неё и заполнить​Set ws =​

​RowFind_ll = Selection.Row​ Set xlsWb =​ a&, n&, b&​ As Object Dim​
​ диапазон A1 в​ не знал эту​ мыши приобретает вид​Юрий М​ других открытых файлов​
​ прописать​
​ индексу. В чем​
​Workbooks(«Книга1.xls»).Activate​ книги?​: Octavian.vs, так сохраните​ запустить макрос :)​ в ней Шапку(действие1).​ nb.Sheets(1)​
​next RowFind_ll​
​ xlsApp.ActiveWorkbook Set xSh​
​ Set xlsApp =​
​ a&, n&, b&​

CyberForum.ru

Активировать нужную книгу без привязки к наименованию книги (Макросы/Sub)

​ Книга1 Set oRange​​ функцию, но как​
​ песочных часов.​: А как Excel​ и где хранятся​200?’200px’:»+(this.scrollHeight+5)+’px’);»>ИмяКниги=Activeworkbook.Name​ проблема, лично мне,​или​Казанский​ в корень диска​А так он​ Далее переключиться в​With ws​//​
​ = xlsWb.ActiveSheet Set​ GetObject(, «Excel.Application») For​ Set xlsApp =​ = oSheet.Range(«A1») oRange.Value​ обычно чувствуюешь и​К сожалению. А​ должен догадаться КАКУЮ​ не известно.​. По индексу,​ не понятно. Код​Workbooks(«Книга1.xlsx»).Activate​:​ или в какую-нибудь​ должно быть:​ книгу «This» и​.Select​Пробовал указывать перед​ r = xSh.ActiveCell​ Each xlsWb In​ CreateObject(«Excel.Application») ‘ xlsApp.Visible​ = «Данные» ‘вносим​ пробуешь как будто​ Application.InputBox позволяет осуществлять​ именно из открытых​В какую сторону​
​ как советовал​
​ Ваш должен выглядеть​
​Dendibar​
​PuLbKa​
​ папку, отправьте и​
​Set sh =​
​ выполнить действие2. Результаты​
​.Name = "Результат"​
​ этой строчкой sh.select​
​ txt = r.Text​
​ xlsApp.Workbooks If xlsWb.Name​
​ = True Set​
​ в него данные​

​ есть еще на​ выбор диапазона мышью​

​ книг нужно активировать?​​ смотреть?​Udik​
​ примерно так (макрорекордер​
​: Добрый день!​
​, напишите на Форуме​
​ удалите после файл.​

​ wb.Sheet(a) (наверное)​ действия 2 занести​B)​.Rows(«1:4»).Select​

​ — тоже не​​ ‘.ActiveCelltxt = GetObject(,​ = «Book.xlsx» Then​ xlsWb = ActiveWorkbook​ ‘сохраняем файл с​ природе такая функция​ только на той​jfd​iba2004​, тоже можно. Только​ пишет правильно, но​
​Вопрос может глупый,​
​ имя активной книги.​
​Octavian.vs​
​Хотел чтобы этот​
​ в новую книгу.​

​ActiveWindow.FreezePanes = True​​ переключается​
​ «Excel.Application»).ActiveCell?Созрел ещё один​ MsgBox «Нужная книга!»​
​ n = xlsWb.Sheets.Count​ новым названием в​ ActiveWorkbook.Path помимо ThisWorkbook.Path!​ книге на которой​: Спасибо.​: Мне думается, что​ за индексами придётся​ кривовато)​ но только начал​PuLbKa​: , спасибо, об​ цикл по листам​Russia​End With​Windows(«Лист1″).Activate — Можно​ вопрос по этой​ End If Next​ Set xlsSh =​ указанное место на​У Вас тоже​ он был запущен.​КАк все далеко​ нужно создать что-то​очень​200?’200px’:»+(this.scrollHeight+5)+’px’);»>Sub tt()​
​ свои попытки работы​
​: workbooks("Имя").activate​
​ этом уже думал,​
​ книги прошелся, поэтому​
​: Зачем активировать листы?​
​For Each sh​
​ как-нибудь обойтись без​ "бородатой" теме:​
​ Set xlsWb =​
​ xlsWb.Sheets(1) a =​
​ диск 'методом SaveAs​
​ так иногда происходит?​
​ Причем мышью можно​
​ зашло однако. А​
​ типа ListBox (TextBox)​
​тщательно следить.​

​Application.ScreenUpdating = False​​ с макросами, подскажите​Казанский​ возможно есть более​ написал это:​ Запиши нужные листы​ In wb.Worksheets​ этой строчки, т.к.​Как из VB6​ xlsApp.ActiveWorkbook n =​ xlsSh.Cells(Rows.Count, 1).End(xlUp).Row Set​ oWbk.SaveAs «D:Книга1.xls» oWbk.Close​ Как бы чуешь?​ выбрать только если​ я думал ограничится​​ в который будут​​МВТ​Workbooks(«Книга1»).Sheets(«Лист1»).Range(«9:9»).Copy Destination:=Workbooks(«Книга2»).Sheets(«Лист1»).Range(«A9»)​​ пожалуйста. Если повторяюсь​​: Я так делаю​ изящные решения?​​For Each sh​​ в переменные -​

​Set sh =​​ надо будет вытаскивать​ записать в активную​ xlsWb.Sheets.Count Set xlsSh​ xlsSh = xlsWb.Sheets(2)​ ‘закрываем файл Книга1​Sergey112233​ не установлен запрет​ паузой (например вызовом​
​ собираться имена открытых​
​: Если Вы АБСОЛЮТНО​Application.ScreenUpdating = True​
​ - извините, много​ он ругается​
​The_Prist​ In wb.Worksheets​
​ и обращайся к​
​ wb.Sheets(a(i))​ имя книг и​
​ ячейку Книги.xls формулу.​
​ = xlsWb.Sheets(1) '​
​ b = xlsSh.Cells(Rows.Count,​ Kill "D:Книга1.xls" 'удаляем​
​: Уважаемые форумчане.​ на Application.ScreenUpdating, как​ Inputboxa) в выполнении​
​ файлов. Есть что-то​
​ уверены, что у​
​End Sub​
​ форумов сегодня облазил,​
​PuLbKa​

​: Нету. Невозможно отправить​Проверил — лист​ ним.{/post}{/quote}​lastrow = sh.Cells(8,​ т.п. Мне казалось​В VBA это​

​ а дальше -​​ 1).End(xlUp).Row End Sub​ файл Книга1 с​Есть такой код:​
​ то долго не​ макроса и открытием​ их объединяющее, например,​

excelworld.ru

VBA: В процессе выполнения макроса выбрать мышью активное окно (книгу)

​ Вас будет открыто​​Dendibar​
​ нашел близкие вопросы​: Значит, используете неправильное​ что-то, что еще​ один только берет.​
​Так и делал!​ 5).End(xlDown).Row​ что это проще​ пишется так:​ косяк :) a​dzug​ диска ‘oWbk.Quit????????? End​1. Открыта Книга113​ мог понять почему​ другой книги, но​ расширение? Но я​ ровно 2 книги​: Спасибо за ответы!​ и ответы, но​ имя. Выполните в​
​ не создано. А​Может нужно так​

​ Стопорится на том​​k = 4​ делает.​ActiveCell.FormulaR1C1 = «=R[+1]C+R[0]C[-2]»А​ = xlsWb.Sheets(1).Cells(Rows.Count, 1).End(xlUp).Row​: Увы, не работает..​ Sub​2. С помощью​ не работает выбор​ не дает открыть​ с такими проблемами​ причем, название одной​Наверное непонятно сформулировал​ на свой пример​ окне Immediate for​ именно так выглядит​ написать?​ моменте что указал​ ‘заполнение под «шапкой»​
​P.S.Заранее спасибо за​

​ вот из VB6​​ Set xlsSh =​
​dzug​dzug​

​ кода создаем новую​​ мышью, когда в​ другую книгу​ не сталкивался и​

​ из них Вы​​ вопрос:​ не могу применить​ each w in​ несохраненная книга -​

​For i =​​ в теме.​For RowFind_ll =​
​ любой совет, решение.​ записать не получается​ xlsWb.Sheets(2) b =​:​: Активацию между книгами​ книгу Книга1. Здесь​

​ другом макросе все​​jfd​ это всего лишь​ знаете, то можно​В том месте​ эти ответы.​
​ workbooks:debug.? w.name:nextПолучите список​ её пока вроде​ 0 To UBound(a)​Hugo​ 8 To lastrow​

​Johny​​ . Пробовал по​ xlsSh.Cells(Rows.Count, 1).End(xlUp).Row End​dzug​ смотрите в прилагаемом​​ она еще не​ было хорошо. )​: Пауза в выполнении​​ моё предположение. Сейчас,​ так​ где мне макрорекордер​Проблема вот в​ книг. Скопируйте нужное​

​ как нет и​​ind = 0​: Так именно в​ ‘ цикл по​: Я дико извиняюсь,​

​ разному (см.мой пост​​ Sub​
​: Проверил ещё раз.​ файле.​ сохранена на диске,​Sergei_A​ макроса во время​ к сожалению, времени​200?’200px’:»+(this.scrollHeight+5)+’px’);»>Sub tt()​ написал: Windows(«Книга 2.xlsx»).Activate​ чем: макрос, который​

​ имя и вставьте​​ пути до неё​For Each sh​ этой строке ссылки​ ТП​ но можно ли​ № 16)в т.ч.​Устранил​ Не работает ..​new_see​

​ а находится в​​: Я не понял​ которой мышью тыкается​ мало, попробуйте что-нибудь​Dim wb1, wb2​ , при пользовании​ я сделал будет​ в код.​

​ тоже нет. Поэтому​​ In wb.Worksheets​ на лист нет.​RowFind_l = RowFind_ll​ узнать, что вообще​ и так:​
​Sub main() Dim​dzug​: Как создать новую​
​ памяти ПК.​ о чем это​ нужная книга и​ подобное в Нете​
​ As Workbook​ макросом, файл всегда​ применятся для эксель​
​Апострофф​

​ сохранять книгу в​​Russia​
​Если бы было​n = 1​

​ этот код делает?​​xlsWb.ActiveCell.FormulaR1C1 = «=R[+1]C+R[0]C[-2]»пробовал​ xlsApp As Excel.Application​​: Я в Excel​ книгу с заданным​3. В ячейку​ Вы.​ она становится активной,​ поискать, а м.б.​Dim Rng As​ будет называться по-разному,​ файлов с различными​: Можете подсказать как​ любом случае надо.​:​ типа так:​ ‘порядковый номер​И очень непонятно​​ и с​ Dim xlsWb As​ запускал, там пашет,​ именем?​ Книги1 вносим данные.​jfd​ все действия макроса​ более знающие люди​ Range​ поэтому не подходит,​ наименованиями, но код​ это сделать?​Octavian.vs​Russia​sh.Range(sh.Cells(RowFind_l, 4), sh.Cells(lastrow,​Range(Cells(RowFind_l, 4), Cells(lastrow,​

​ вот это: Set​​xlsApp​ Excel.Workbook Dim xlsSh​ сейчас посмотрю в​

​Например​​4. Сохраняем Книгу1​: Хотел малой кровью​ идут в активной​

​ помогут.​​Set wb1 =​​ чтобы название было​
​ ниже строго привязан​Catstail​

planetaexcel.ru

Запомнить директорию активной книги. VBA

​: Спасибо! Просто были​​: хотел написать​
​ 4)).Select​ 4)).Select ‘ —>​ wb = ThisWorkbook.​, и с​ As Excel.Worksheet Dim​ VB6​Sub CreateWorkbook() Set​ на диске.​ отделаться. Спасибо за​ книге. Если так​Удачи!​ ThisWorkbook​ «Книга 2.xlsx», надо,​
​ к копированию в​
​: 1: Открыть VBA​

​ сомнения которые теперь​​Hugo​

​вот это было​​ Здесь почему то​ И где эта​xSh​ a&, n&, b&​dzug​

​ NewWorkbook = Workbooks.Add​​5. Закрываем Книгу1.​ пример.​

​ конечно возможно.​​k61​With wb1.Sheets(«Лист1»)​ чтобы название сюда​

​ определенный файл («Книга​​ — [Alt+F11]​ окончательно развеяны.​: Это уже ближе.​ бы «так и​ стопорится из-за того​ «wb» используется?​
​.Сам задал вопрос,​ Set xlsApp =​: Вылазит вот такая​ End Subсоздает книгу​6. Удаляем Книгу1​jfd​ber$erk​: Код в Книге2​
​Set Rng =​ менялось в зависимости​ 2.xlsx»), а файлы​

planetaexcel.ru

Как сделать активной новую Книгу?

​2: Нажать [Ctrl+G]​​Strobery​
​Но ведь если​
​ делал».​
​ что не переключается​ikki​ сам и отвечаю.​ GetObject(, «Excel.Application») Set​ «петрушка» на восьмой​ с именем по​ с диска.​
​:​: В коде макросе​
​Sub www() Workbooks(«Книга1»).Activate​ Intersect(.UsedRange, .Range(«9:9»))​
​ от названия файла.​
​ будут называться по​ (или ищите в​
​: У меня есть​For Each sh​Но тогда селект​
​ на другую книгу.​: а вот эта​
​Методом «тыка» получилось​ xlsWb = xlsApp.ActiveWorkbook​ строке.. А на​ умолчанию,​7. Закрываем Excel,​Казанский,​ если указать ActiveWorkbook.ActiveSheet.range…​ End Sub​
​End With​ Находил на форумах​ другому. Если меняю​ меню окно​ книга1 и кнопка(Лист1)​ In wb.Worksheets​ уже не нужен,​
​ Подскажите пжл, как​ строка у вас​ сделать так:​ n = xlsWb.Sheets.Count​ седьмой строке значение​а как изменить​
​ в котором была​Спасибо, так и​ то код как​jfd​Rng.Select​ решения, но почему-то​ Windows(«Книга 2.xlsx»).Activate на​Immediate​ при нажатии которой​то в sh​ разве что как​ исправить.​ нормально срабатывает?​GetObject(, «Excel.Application»).ActiveCell.FormulaR1C1 =​ Set xlsSh =​ объектной переменной xlsWb​ имя, чтобы создалась​ создана Книга1.​ сделал.​ раз будет выполняться​: Извините, создается впечатление​For Each wb2​ не получается, ниже​ ActiveSheet.Activate, то копирование​)​ Открываетия Форма1.​ уже есть ссылка​ финальное действие -​Selection.Find(What:=»», After:=ActiveCell, LookAt:=xlPart).Select​lastrow = sh.Cells(8,​ «=R[+1]C+R[0]C[-2]»​ xlsWb.Sheets(1) a =​

​ не присваивается..​​ не ‘Книга1’,​Подскажите, пожалуйста, два​Inter_E​

CyberForum.ru

Как создать новую книгу с заданным именем?

​ в выбранной книге​​ что Вы не​ In Workbooks​ пытаюсь вытащить название​
​ происходит в «Книга​
​3: Скопировать в​В форме1 есть​ на лист, и​ показать юзеру результат.​RowFind_ll = Selection.Row​
​ 5).End(xlDown).Row​Russia​ xlsSh.Cells(xlsSh.Rows.Count, 1).End(xlUp).Row Set​
​Запускать из VB6..​а например ‘Моя​

​ вопроса.​​: Добрый день!​ (хотя вроде как​

​ удосужились прочесть вопрос.​

CyberForum.ru

Обработка активной книги Excel

​If wb2.Name <>​​ файла в ячейку​ 1.xlsx», так как​ окно​ текст бокс1 и​Set sh =​Russia​next RowFind_ll​Johny​: Добрый вечер!​
​ xlsSh = xlsWb.Sheets(2)​
​dzug​ книга’​1. В пункте​В ходе выполнений​ это по умолчанию)​Юрий М​ wb1.Name Then Exit​ А1 Книги 2,​ ее считает активной.​Immediate​ кнопка1, при нажатии​ wb.Sheets(a(i))​: Пробовал:​next sh​: lastrow = sh.Cells(8,​Задаю листы.​ b = xlsSh.Cells(xlsSh.Rows.Count,​

​: Так?​​new_see​ 2, где Книга1​ макроса, нужно запоминть​Казанский​: Это почему? Вместо​ For​ дальше пытаюсь добавить​ Можно ли как-то​код for each​ кнопки открывается​совершенно лишнее, и​Range(sh.Cells(RowFind_l, 4), sh.Cells(lastrow,​ikki​ 5).End(xlDown).Row​Set wb =​ 1).End(xlUp).RowEnd Sub​Sub main() Dim​

​: NewWorkbook.Windows(1).Caption = ‘Моя​​ еще не сохранена,​

​ директорию где находиться​​: Создайте форму со​

​ «Книга1» подставляем выбранное​​Next​ содержимое этой ячейки​

​ активировать книгу без​​ w in workbooks:debug.?​книга2 Я активирую​ даже вероятно только​ 4)).Select​

​: имхо, здесь имеем​​Что за переменная​ ThisWorkbook​Спасибо. Всё заработало.​ XL As New​ книга’​ есть ли возможность​
​ текущая книга. Затем​

​ свойством ShowModal=False, надписью​​ значение из Лист/КомбоБокса,​
​Application.ScreenUpdating = False​ туда куда надо,​ привязки к названию?​ w.name:next4: Поставить курсор​ книгу1, (делаю нужные​ мешает.​и​ довольно дикую смесь​ «sh»?​Sheets(a).Select​ Только вместо xlUp​ Excel.Application, xlsSh XL.Workbooks.Open​спасибо​ активации Книги113, затем​ я создаю макросом​

​ «Выберите книгу» и​​ как предлагалось выше.​Rng.Copy Destination:=wb2.Sheets(«Лист1»).Range(«A9»)​ но все равно​ Например, активировать книгу,​ ввода на строку​ процедуры) и теперь​Или одно, или​
​sh.Range(Cells(RowFind_l, 4), Cells(lastrow,​ результатов работы макрорекодера​Russia​
​Sheets(a(i)).Columns(«E:F»).Cut​ надо написать -4162​

​ App.Path & «Book.xlsx»​​dzug​

​ активации Книги1. Т.е.​​ новую книгу. Суть​ кнопкой. В коде​ber$erk​Application.ScreenUpdating = True​ берет не нужную​ в которой установлен​ с введенным кодом​ мне нужно активировать​ другое.​ 4)).Select​ и каких-то (не​: Извиняюсь пару строчек​Columns(«A:A»).Select​ . Понять это​ Set XL =​: Необходимо определить количество​ здесь передача активации​ в том что​ кнопки напишите​: все открытые файлы​End Sub​ ячейку, а ячейку​ курсор? Или по​5: нажать Enter​

​книгу2 но так​
​Russia​//​ очень понятных) попыток​ забыл захватить. Я​Selection.Insert Shift:=xlToRight​ помогла соседняя тема​ XL.ActiveWorkbook.Sheets.Application XL.Visible =​ заполненных строк первого​ между книгами возможна.​ я хотел сохранять​Private Sub CommandButton1_Click()​ Excel​В противном случае​ из книги 1.​ какому-то иному признаку.​Но есть подозрение,​
​ как имя книги​: Да я тоже​Пойду проверять.​ их доработки.​ писал. И вся​
​Set nb =​Работа с excel​
​ True Dim a&,​
​ и второго, по​2. Пункт7 -​ новую книгу туда​ Unload Me MainMacro​Sub ListAll() Dim​ соблаговолите ВНЯТНО объяснить,​200?’200px’:»+(this.scrollHeight+5)+’px’);»>​ Подскажите пожалуйста.​ что сделать активной​ находится в текст​ об этом думал,​
​Hugo​много мусора -​ используется. И хотелось​
​ Workbooks.Add​ ячейками​ n&, b& n​ индексу, листов активной​
​ как закрыть Excel,​
​ же где находилась​ End Sub​ wb As Workbook​ что именно Вы​Sub Тест()​200?’200px’:»+(this.scrollHeight+5)+’px’);»>Sub Тест()​ Вы хотите неоткрытую​ боксе я не​ но просто макрос​: Ну значит недопробовали:)​ те же ActiveWindow.FreezePanes​ бы что бы​Set ws =​Ещё раз спасибо.​ = XL.Sheets.Count Set​ книги Excel (книга​ в котором создавалась​
​ прежняя книга. Не​, где MainMacro​ For Each wb​
​ делаете и что​’​
​’​ книгу?​ знаю как это​ не работал, вот​Только я в​ = True, .Rows(«1:4»).Select​ когда я писал​
​ nb.Sheets(1)​Не могу прочитать​​ xlsSh = XL.Sheets(1)​​ открыта). На седьмой​​ Книга1, а Книга113​​ могу придумать эту​ — макрос, который​
​ In Workbooks MsgBox​ ожидаете получить в​
​’ Тест макрос​’ Тест макрос​

CyberForum.ru

VBA Как переключать окна/книги?

​Pavel55​​ сделать.​
​ я и подумал,​
​ Вашем примере нигде​ и др.​
​ sh.select — становилась​
​With ws​
​ название подключаемой библиотеки..​
​ a = xlsSh.Cells(Rows.Count,​
​ строке переменной xlsWb​ оставалась бы открытой.​
​ идею…​ работает с активной​
​ wb.Name Next End​
​ результате​
​’​
​’​
​: Казанский совершенно прав.​
​Вот код​
​ что может нужно​ не видел, где​
​возможно, проще озвучить​ активной книга ThisWorkbook,​
​.Select​ Напишате пожалуста название​ 1).End(xlUp).Row Set xlsSh​ , значение не​
​ Здесь, видимо, тот​
​Заранее благодарен.​ книгой.​
​ Sub​Dendibar​’​’​ Но при условии,​Private Sub CommandButton1_Click()​ задать.​ эта sh определяется…​
​ саму задачу?​
​ а не получается​
​.Name = «Результат»​

​ отдельно.Microsoft Excel 12.0​
​ = XL.Sheets(2) b​ присваивает ???​ же вопрос активации.​С уважением, Inter_E​
​Форма запускается стартовым​jfd​: StoTisteg, большое спасибо!​Range (A1) =​Windows(«Книга 1.xlsx»).Activate​ что книга открыта.​ ‘Открываю Книгу2 Dim​Спасибо, Hugo!​

​Russia​Russia​

​ — не переключается​​.Rows(«1:4»).Select​ Object LibraryРазобрался с​ = xlsSh.Cells(Rows.Count, 1).End(xlUp).Row​Спасибо за ответ.​
​Как Вы понимаете,​Alex_ST​ макросом из одной​: Юрий М, потому​ Вашим способом все​

​ ActiveWorkbook.Name​​Rows(«9:9»).Select​ Если книга не​ wb As Workbook​

​Юрий М​: Сообщение от 05.05.2011,​

​: Блин. Хорошо. Как​​ на окно этой​ActiveWindow.FreezePanes = True​

​ библиотекой..Спасибо.Да простят меня​ End Sub​

​Sub main() Dim​​ действия с Книгой1​: ThisWorkbook.Path​ команды​ что этот способ​ получилось.​Windows(«Книга 1.xlsx»).Activate​Selection.Copy​ открыта — ее​ Set wb =​: Возвращаясь к переключению​ 17:28​ сделать активным этот​ книги, остается в​End With​
​ администраторы за поднятие​Апострофф​ xlsApp As Object​ должны происходить в​ответ > Alex_ST​UserForm1.Show​ очевиден и предполагает​Всем остальным тоже​Rows(«9:9»).Select​Windows(«Книга 2.xlsx»).Activate​

​ нужно сначала открыть,​ Workbooks.Open(Filename:=’C: ‘ &​
​ между книгами:​
​в середине указывается.​
​ лист? А потом​
​ новой книге и​
​lastrow = sh.Cells(8,​ темы с «двухлетней​
​: В том то​ Dim xlsWb As​
​ скрытом от пользователя​
​: Спасибо, я изменил​
​Юрий М​
​ знание названия файла​
​ большое спасибо за​
​Selection.Copy​

​Rows(«9:9»).Select​ а уж затем​
​ TextBox1 & ‘.xls’)​Windows(«Нужная_Книга.xls»).Activate​
​Hugo​ другой лист из​
​ выдает ошибку.​ 5).End(xlDown).Row​
​ бородой» , но​ и дело, что​ Object Dim xlsSh​ режиме. Постоянно открыта​
​ на «ActiveWorkbook.Path» и​
​: Попробуйте тогда .Wait​ нужной книги.​
​ помощь!​Windows(«Range (A1).Value»).Activate​ActiveSheet.Paste​ активизировать.​ ‘ Workbooks(‘Книга1.xls’).Worksheets(‘Лист1’).Activate ‘Имя​Octavian.vs​: Да, там я​ другой книги (ThisWorkbook)?​
​lastrow = sh.Cells(8,​
​k = 4​
​ вопрос стопроцентно по​
​ книга Excel открыта​

​ As Object Dim​​ только Книга113.​ кажется все будет​А Application.InputBox не​А кроме получения​jfd​Rows(«9:9»).Select​
​Range(«J5»).Select​мне кажется. тут​ последней заполненой ячейки​: Добрый день,​

​ не вникал.​Johny​

​ 5).End(xlDown).Row — это​​ ‘заполнение под «шапкой»​ этой теме.​ и название у​ a&, n&, b&​Sub Кнопка1_Щелкнуть() Dim​

​ работать положенно. Сейчас​​ пробовали?​
​ списка всех открытых​: Добрый день!​ActiveSheet.Paste​End Sub​

​ ещё важную роль​​ Const iRow2 =​На просторах интернета​Но вот это​: ikki, Согласен полностью.​ мои опыты, чтобы​

​For RowFind_ll =​​Открыта книга Эксель,​ неё может быть​ Set xlsApp =​ oExcel As New​ окончательно проверю!​jfd​ фалов и выбора​Банальная вроде вещь,​Range(«J5»).Select​Оформляйте коды тегами​ играет указано ли​

​ 65536: iClm =​​ нашел код отправки​ как понимать?​russia, попытайтесь ещё​ производил операции с​ 8 To lastrow​
​ на листе выделена​ разное. Обращаться надо​ CreateObject(«Excel.Application») ‘ xlsApp.Visible​ Excel.Application ‘Запускаем Excel​

​Inter_E​​: Нашел что Wait​ из него одного,​ а потратил кучу​
​End Sub​ (кнопка #)​
​ расширение файла.​ ‘A’ iRws =​
​ сообщения с вложением​For Each sh​ раз описать, для​
​ листом sh (книге​ ‘ цикл по​ одна ячейка.​ к АКТИВНОЙ книге..​ = True Set​

​ oExcel.Visible = True​​: Спасибо, все нормально​
​ —​ других способов нет?​
​ времени и не​
​StoTisteg​Udik​
​На Windows, где​
​ Columns(iClm).Rows(iRow2).End(xlUp).Row ??????????????????????????? ActiveWorkbook.SaveAs​

​ из Excel, но​​ In wb.Worksheets​
​ чего нужен сей​ где находиться макрос).​ ТП​Как из VB​

​В Вашем коде​​ xlsWb = xlsApp.ActiveWorkbook​ ‘Делаем его видимым​
​ пошло, с АктивВоркБук.Пазс​

​это метод позволяет приостановить​​Sergei_A​ нашел ничего.​
​: Как он будет​: по номеру типа​
​ в найстройках не​ Filename:= _ ‘C:123​
​ т. к. активная​Set sh =​

​ макрос?​​ Работает. Но если​RowFind_l = RowFind_ll​

​ 6 узнать что​​ выдаёт ошибку на​ n = xlsWb.Sheets.Count​ Dim oWbk As​ТолькоУчусь​ работу Excel на​

​: Я бы сделал​​Есть файл1 с​ называться у Вас,​
​ такого​ указано — отображать​
​ ‘ & Cells(iRws,​ книга является вновь​

​ wb.Sheets(a(i))​Johny​ задавать sh.cells(…)… -​n = 1​
​ записано в активной​ строке:​

​ Set xlsSh =​ Excel.Workbook ‘Создаем новую​
​: Лучше как Алексей​ указанное вами время,​
​ немодальную форму (похожую​ макросом (кроме макроса​
​ ведомо только Вам.​
​200?’200px’:»+(this.scrollHeight+5)+’px’);»>​ расширения файлов нужно​

​ iClm) & ‘.xls’​​ созданной и не​

​Johny​​: Зачем активировать листы?​

​ то выдает ошибку​​ ‘порядковый номер​
​ ячейке ?​
​Dim XL As​ xlsWb.Sheets(1) a =​
​ книгу Книга1 Set​ предложил, так как​ сняв нагрузку с​
​ на msgbox) с​ ничего не имеет),​
​ Если Вы знаете​Public Sub test()​ делать так​
​ End SubЗаранее благодарен​ имеет своего «реального»​

​: Здесь имеется ввиду​​ Запиши нужные листы​ на подобии вышеописанного.​Range(Cells(RowFind_l, 4), Cells(lastrow,​Пробовал так:​ New Excel.Application, xlsSh​ xlsSh.Cells(Rows.Count, 1).End(xlUp).Row Set​ oWbk = oExcel.Workbooks.Add()​
​ это «…текущая книга…».​

​ процессора. Используется для​​ текстом «​ есть также другие​
​ имя книги, то​

planetaexcel.ru

VBA отправка созданной (активной) книги через outlook

​Debug.Print Application.Workbooks(1).Name​​При открытой книге​
​ ||||||Strobery||||||​ адреса, строчка кода​ активный лист.​ в переменные -​Set wb =​ 4)).Select ‘ —>​Dim xSh As​dzug​ xlsSh = xlsWb.Sheets(2)​ Dim oSheet As​Inter_E​ демонстраций — чтобы​Выберите одну из открытых​
​ открытые файлы. После​ так и пишите​End Sub​

​Workbooks(«Книга1»).Activate​​Masalov​ ( .Attachments.Add ActiveWorkbook.FullName)​Johny​ и обращайся к​ ThisWorkbook​

​ Здесь почему то​​ Excel.Worksheet, xlsApp As​:​ b = xlsSh.Cells(Rows.Count,​ Excel.Worksheet Set oSheet​

​: Да, спасибо, но​​ пользователь успел увидеть,​ книг Excel, и​ запуска макроса из​ — Workbooks(). Ещё​только в номерах​А если вы​: например:​ не может подтянуть​: Range(Cells(RowFind_l, 4), Cells(lastrow,​ ним.​Sheets(a).Select​

​ стопорится из-за того​​ Excel.Application, xlsWb As​dzug​ 1).End(xlUp).Row End Sub​

planetaexcel.ru

Активация книг с именем находящимся в текстбоксе (Excel)

​ = oWbk.Worksheets.Item(«Лист1») ‘Находим​​ у меня код​ что происходит, для​ нажмите ОК.​ файл1 надо выбрать(указать​
​ один способ —​ не запутайтесь​ в настройках Windows​Windows(Me.TextBox1.Value).Activate​
​ файл, может есть​ 4)).Select ‘ —>​Russia​Sheets(a(i)).Columns(«E:F»).Cut​
​ что не переключается​ Excel.Workbook, xlsSh As​: Sub main() Dim​dzug​ Лист1 oSheet.Name =​ макроса расположен на​
​ ожидания завершения выполнения​
​» и одной кнопкой​ мышью, сделать активным)​ завести переменную, скажем,​.​ (в свойствах папки)​то, нет?​ какие-нибудь пути решения?​ Здесь почему то​: Задача. Мне необходимо​Columns(«A:A»).Select​ на другую книгу.​ Excel.Worksheet Dim txt$,​ xlsApp As Excel.Application​: Sub main() Dim​ «Новый лист» ‘Присваиваем​ Personal.book и поэтому​ какой-либо внешней операции​

​ ОК. По кнопке​​ один из открытых​
​ ИмяКниги и в​
​МВТ​

CyberForum.ru

​ указали — отображать​

3 / 3 / 0

Регистрация: 12.12.2015

Сообщений: 174

1

09.02.2018, 14:52. Показов 5606. Ответов 16


Студворк — интернет-сервис помощи студентам

Добрый день уважаемые! , подскажите пожалуйста, как активировать окно Excel запущенного из стороннего приложения?
Создал макрос. Из Excel запускаю другое приложение, в процессе работы это приложение запускает свою сессию Excel и открывает в ней свой документ. Мне нужно переключить фокус в эту сессию, внести изменения в документ и распечатать. Как это сделать?



0



6875 / 2807 / 533

Регистрация: 19.10.2012

Сообщений: 8,562

09.02.2018, 15:20

2

Лучший ответ Сообщение было отмечено Sasanik как решение

Решение



0



3 / 3 / 0

Регистрация: 12.12.2015

Сообщений: 174

10.02.2018, 08:35

 [ТС]

3

Hugo121, Добрый день! Вам, Предложенный вариант — это для 32 бит офиса. Не самое страшное Макрос позволяет получить названия всех открытых окон Excel, уже хорошо. Но в моем случае, даже зная имя открытого окна, я не могу к нему обратится . Похоже заковыка, в том, что созданный файл находится в скрытой системной папке. Вот по этому пути «C:UsersЯAppDataLocalТУТТУТ ВСЁtmpНАШЕ». Вопрос в том, что в ходе процесса это окно уже активно, как к нему обратиться?



0



6875 / 2807 / 533

Регистрация: 19.10.2012

Сообщений: 8,562

10.02.2018, 18:57

4

Цитата
Сообщение от Sasanik
Посмотреть сообщение

Вопрос в том, что в ходе процесса это окно уже активно, как к нему обратиться?

так ведь именно на это я и дал ссылку:

Цитата
Сообщение от Shersh
Посмотреть сообщение

Наверно, можно проще —
Visual BasicВыделить код
1
2
Dim wb As Workbook
Set wb = GetObject(«Книга2.xls») ‘Книга2.xls — заголовок окна книги, открытой в другом процессе



0



Эксперт WindowsАвтор FAQ

17993 / 7619 / 890

Регистрация: 25.12.2011

Сообщений: 11,352

Записей в блоге: 17

14.02.2018, 07:13

5



0



3 / 3 / 0

Регистрация: 12.12.2015

Сообщений: 174

07.03.2018, 18:42

 [ТС]

6

Dragokas, Доброго времени суток Вам! К сожалению предложенное Вами, на моей машинке не реализуемо . Попросту библиотеку установить нет возможности, нет прав на администрирование.



0



Эксперт WindowsАвтор FAQ

17993 / 7619 / 890

Регистрация: 25.12.2011

Сообщений: 11,352

Записей в блоге: 17

07.03.2018, 19:00

7

Её не нужно устанавливать. Её нужно подключить через Tools -> references. Или зарегистрировать от имени пользователя с ограниченными правами: Как правильно зарегистрировать TLB ?
Вообще, можно переписать код без использования tlb.



0



3 / 3 / 0

Регистрация: 12.12.2015

Сообщений: 174

08.03.2018, 20:25

 [ТС]

8

Hugo121, Доброго времени суток Вам,

Цитата
Сообщение от Hugo121
Посмотреть сообщение

так ведь именно на это я и дал ссылку:

опробовано и это … без успешно. Делаю так — Запускаю макрос из своего Excel-файла, тот запускает скрипт для внешней программы, в свою очередь внешняя программа запускает свой, новый процесс Excel, в котором открыт файл с 3 страницами, и макросом для форматирования текста. Имя открытого окна, с новым файлом я нахожу с помощью Вашего макроса. Но активировать его — Не могу . Команда — Windows(wb.name).Activate сообщает об ошибке. Где собака порылась? Пока не ведомо мне…



0



Hugo121

6875 / 2807 / 533

Регистрация: 19.10.2012

Сообщений: 8,562

08.03.2018, 21:07

9

Зачем вообще нужно активировать окно? В 99,9% задач это не нужно.
Но вообще думаю нужно указать процесс. т.е.

Visual Basic
1
нужныйэксель.Windows(wb.name).Activate



0



3 / 3 / 0

Регистрация: 12.12.2015

Сообщений: 174

09.03.2018, 07:58

 [ТС]

10

Hugo121, Добрый день Вам, Всё просто:- в моём 0,01% случае, есть необходимость вносить правки во вновь созданном документе. Потому и активация для работы в нём. Можно и без активации, всё равно у меня ошибка при обращении к книге .
Осталось понять, что такое

Цитата
Сообщение от Hugo121
Посмотреть сообщение

нужныйэксель

в

Цитата
Сообщение от Hugo121
Посмотреть сообщение

нужныйэксель.Windows(wb.name).Activate

, и где его увидеть… В прочем пойду на работу, увижу.



0



6875 / 2807 / 533

Регистрация: 19.10.2012

Сообщений: 8,562

09.03.2018, 13:17

11

нужныйэксель — это смотря в каком коде. В этой теме это возможно wb.parent, в других кодах обычно это xl или objxl. Посмотрите там на работе



0



Sasanik

3 / 3 / 0

Регистрация: 12.12.2015

Сообщений: 174

14.05.2018, 17:47

 [ТС]

12

Hugo121, Спасибо! Нужный «эксель» определил, у меня окно — «xl». Дольше искал как закрыть всё после обработки.

Visual Basic
1
2
3
4
5
6
7
    xl.Windows(wb_n.Name).Activate
      ' дорабатываем и сохраняемся.
    wb_n.SaveAs ThisWorkbook.Path & "" & Name, xlExcel12   'Сохраняем новую книгу с именем "объекта".
      ' закрываем саму книгу.
    wb_n.Close
' и только это помогло закрыть остатки.
Application.xl.Quit



0



6875 / 2807 / 533

Регистрация: 19.10.2012

Сообщений: 8,562

14.05.2018, 22:42

13

А Вы знаете что Name (вот так, отдельно) — это не имя, это у VBA есть такое действие? Замените это имя переменной на что-то нейтральное, например да хоть на name_. Пока не поздно…
Первая строка лишняя, а в седьмой строке думаю лишнее «Application.»



0



Казанский

15136 / 6410 / 1730

Регистрация: 24.09.2011

Сообщений: 9,999

15.05.2018, 00:49

14

Hugo121, да ниче, работает

Visual Basic
1
2
3
4
5
6
7
8
9
10
11
12
Sub КосилКосойКосойКосой()
Dim Name
  Name = "Вася"
  Names.Add Name, Name
  Open Name For Output As #1
  Print #1, Names(Name).Name
  Reset
  Name Name As Name & Name
  MsgBox Dir(Name & Name)
  Kill Name & Name
  Names(Name).Delete
End Sub



0



6875 / 2807 / 533

Регистрация: 19.10.2012

Сообщений: 8,562

15.05.2018, 10:48

15

Цитата
Сообщение от Казанский
Посмотреть сообщение

Name Name As Name & Name

— это вообще бомба



0



3 / 3 / 0

Регистрация: 12.12.2015

Сообщений: 174

15.05.2018, 16:25

 [ТС]

16

Hugo121,

Цитата
Сообщение от Hugo121
Посмотреть сообщение

Первая строка лишняя, а в седьмой строке думаю лишнее «Application.»

У меня без первой строки не срабатывает. Фокус программы остаётся на книге из которой запускается макрос. Последнее — проверю на «лишность» .
По поводу «Name» — это я тут, в приведённом фрагменте, оставил это слово, а в коде я его не использую. За уточнение спасибо!



0



6875 / 2807 / 533

Регистрация: 19.10.2012

Сообщений: 8,562

15.05.2018, 23:37

17

А накой там в этом коде нужен этот фокус?
Я ведь говорил вот об этих конкретных семи строках (включая комментарии).



0



Home / VBA / How to Activate a Sheet using VBA

Let’s say you are working with multiple worksheets, and for you, it’s hard to navigate to a sheet using a tab. In this situation, you can use a VBA code to activate any worksheet.

And, to write a VBA code for this you need to use Worksheet.Activate Method. In this post, I’d like to share with you a simple way to write this code to activate or select a worksheet. Before you write this code, you need to understand this method.

In this method, you can specify the worksheet’s name or number which you want to activate. Let’s say you need to activate sheet1, then the code will be:

Worksheets("Sheet1").Activate

Or you can use sheet numbers as well.

Worksheets("1").Activate

So the final code will be:

Sub ActivateSheet1()
Worksheets("Sheet1").Activate
End Sub

Examples: Activate a Worksheet with VBA

In the real life, you can use this method in different ways. Here are some of them.

1. Activate a Worksheet on Opening

If you want to activate a specific worksheet every time when you open the workbook then you name that VBA code auto_open.

Sub auto_open()
Worksheets("Sheet1").Activate
End Su

2. Activate a Worksheet and Hide all other

Maybe you want to navigate to a worksheet and hide all the other worksheets from the workbook. You can do this by using the below code.

Sub HideWorksheet()
Dim ws As Worksheet
For Each ws In ThisWorkbook.Worksheets
If ws.Name <> "Sheet1" Then
ws.Visible = xlSheetHidden
End If
Next ws
End Sub

Change the sheet name from the above code to use it further.

Must Read Next

  1. VBA to Create New Sheet
  2. How to Record a Macro in Excel
  3. VBA Option Explicit

VBA is one of the Advanced Excel Skills, and if you are getting started with VBA, make sure to check out there (What is VBA, and Useful Macro Examples and VBA Codes).

Понравилась статья? Поделить с друзьями:

А вот еще интересные статьи:

  • Как активировать ячейку vba excel
  • Как активировать надстройки excel
  • Как активировать функции word
  • Как активировать макросы word
  • Как активировать формулы в word 2010

  • 0 0 голоса
    Рейтинг статьи
    Подписаться
    Уведомить о
    guest

    0 комментариев
    Старые
    Новые Популярные
    Межтекстовые Отзывы
    Посмотреть все комментарии