VBA List all Open Workbooks in Excel. It helps to know all open workbooks name. It is easy to handle and shift between workbooks. We have an option to open multiple workbooks in MS Office Excel. Let us see in the following tutorial how to list open Workbooks in Excel VBA.
Here is the following syntax to List all Open Workbooks in Excel VBA.
For Each Workbook in Application.Workbooks Statements... Next
Where Workbook: It represents Workbook object which is part of workbooks collection.
VBA Code to List all Workbooks in Excel VBA
Let us see the following example macro to List all Open Workbooks in Excel VBA
'VBA List Open Workbooks in Excel Sub VBA_List_All_Open_Workbooks() 'Variable declaration Dim xWorkbook As Workbook Dim sWorkbookName As String Dim iCount As Integer 'Intialise value to a variable iCount = 2 Sheets("WB_Names").Range("A1") = "Names of Available Workbooks" 'Loop through all workbooks For Each xWorkbook In Application.Workbooks Sheets("WB_Names").Range("A" & iCount) = xWorkbook.Name & vbCrLf 'Increase value iCount = iCount + 1 Next End Sub
Instructions to Run VBA Macro Code or Procedure:
You can refer the following link for the step by step instructions.
Instructions to run VBA Macro Code
Other Useful Resources:
Click on the following links of the useful resources. These helps to learn and gain more knowledge.
VBA Tutorial VBA Functions List VBA Arrays in Excel Blog
VBA Editor Keyboard Shortcut Keys List VBA Interview Questions & Answers
Author: Oscar Cronquist Article last updated on March 19, 2019
In this post, I am going to demonstrate how to automatically create a new sheet in the current workbook and list all open workbooks and their sheets using a VBA macro.
The image above shows the new worksheet, it contains the names of the workbooks and corresponding worksheets I have currently open.
Macro code
'Name macro Sub ListWorkbooks() 'Declare variables and data types Dim wb As Workbook Dim ws As Worksheet Dim i As Single, j As Single 'Create a new worksheet and save to object ws Set ws = Sheets.Add 'Go through open workbooks For j = 1 To Workbooks.Count 'Save workbook name to cell A1 and downwards Range("A1").Cells(j, 1) = Workbooks(j).Name 'Iterate through worksheets in given workbook For i = 1 To Workbooks(j).Sheets.Count 'Save worksheet names to cell B1 and cells further right Range("A1").Cells(j, i + 1) = Workbooks(j).Sheets(i).Name 'Continue with next worksheet Next i 'Continue with next workbook Next j End Sub
How to copy the macro to your workbook
- Press Alt+F11 to open the VB Editor.
- Press with right mouse button on on your workbook in the Project Explorer.
- Press with left mouse button on «Insert» and then «Module».
- Copy macro code.
- Press with left mouse button on in code module window to see the input prompt.
- Paste code to code module.
- Return to Excel.
How to run the macro
- Go to «Developer» tab on the ribbon.
- Press with left mouse button on «Macros» button.
- Select «ListWorkbooks» macro.
- Press with left mouse button on «Run» button.
Apply drop-down lists dynamically
This article demonstrates how to automatically create drop-down lists if adjacent data grows, there are two methods explained here. The […]
Auto resize columns as you type
Excel does not resize columns as you type by default as the image above demonstrates. You can easily resize all […]
Automate data entry [VBA]
This article demonstrates how to automatically enter data in cells if an adjacent cell is populated using VBA code. In […]
Basic data entry [VBA]
In this small tutorial, I am going to show you how to create basic data entry with a small amount […]
Calendar with scheduling [vba]
Here is my contribution to all excel calendars out there. My calendar is created in Excel 2007 and uses both […]
Consolidate sheets [vba]
Question: I have multiple worksheets in a workbook. Each worksheets is project specific. Each worksheet contains almost identical format. The […]
Copy a dynamic cell range [VBA]
In this blog post, I will demonstrate some VBA copying techniques that may be useful if you don’t know the […]
Create a Print button [VBA]
This article describes how to create a button and place it on an Excel worksheet then assign a macro to […]
Edit invoice data [VBA]
In a previos post:Excel vba: Save invoice data we added/copied data between sheets. This post describes how to overwrite existing […]
Excel calendar [VBA]
This workbook contains two worksheets, one worksheet shows a calendar and the other worksheet is used to store events. The […]
Hide specific columns programmatically
This article describes a macro that hides specific columns automatically based on values in two given cells. I am also […]
Hide specific worksheets programmatically
This article demonstrates techniques to hide and unhide worksheets programmatically. The image above shows the Excel window and the worksheet […]
How to quickly select blank cells
In this smaller example, column D (Category) has empty cells, shown in the picture above. If your column contains thousands of […]
How to use DIALOG BOXES
A dialog box is an excellent alternative to a userform, they are built-in to VBA and can save you time […]
How to use the Scroll Bar
This article demonstrates how to insert and use a scroll bar (Form Control) in Excel. It allows the user to […]
Identify missing numbers in a column
The image above shows an array formula in cell D6 that extracts missing numbers i cell range B3:B7, the lower […]
Locate a shape in a workbook
This article demonstrates how to locate a shape in Excel programmatically based on the value stored in the shape. The […]
Move a shape [VBA]
This article demonstrates how to move a shape, a black arrow in this case, however, you can use whatever shape […]
Normalize data [VBA]
To be able to use a Pivot Table the source data you have must be arranged in way that a […]
Open Excel files in a folder [VBA]
This tutorial shows you how to list excel files in a specific folder and create adjacent checkboxes, using VBA. The […]
Save invoice data [VBA]
This article demonstrates a macro that copies values between sheets. I am using the invoice template workbook. This macro copies […]
Search two related tables [VBA]
This article demonstrates a macro that automatically applies a filter to an Excel defined Table based on the result from […]
Select and view invoice [VBA]
This post demonstrates how to view saved invoices based on the invoice number using a userform. The userform appears when the […]
Toggle a macro on/off using a button
This article demonstrates how the user can run a macro by press with left mouse button oning on a button, […]
Working with COMBO BOXES [Form Controls]
This blog post demonstrates how to create, populate and change comboboxes (form control) programmatically. Form controls are not as flexible […]
Working with FILES
In this blog article, I will demonstrate basic file copying techniques using VBA (Visual Basic for Applications). I will also […]
Working with TEXT BOXES [Form Controls]
There are two different kinds of text boxes, Form controls and ActiveX Controls. Form controls can only be used on […]
Latest updated articles.
More than 300 Excel functions with detailed information including syntax, arguments, return values, and examples for most of the functions used in Excel formulas.
More than 1300 formulas organized in subcategories.
Excel Tables simplifies your work with data, adding or removing data, filtering, totals, sorting, enhance readability using cell formatting, cell references, formulas, and more.
Allows you to filter data based on selected value , a given text, or other criteria. It also lets you filter existing data or move filtered values to a new location.
Lets you control what a user can type into a cell. It allows you to specifiy conditions and show a custom message if entered data is not valid.
Lets the user work more efficiently by showing a list that the user can select a value from. This lets you control what is shown in the list and is faster than typing into a cell.
Lets you name one or more cells, this makes it easier to find cells using the Name box, read and understand formulas containing names instead of cell references.
The Excel Solver is a free add-in that uses objective cells, constraints based on formulas on a worksheet to perform what-if analysis and other decision problems like permutations and combinations.
An Excel feature that lets you visualize data in a graph.
Format cells or cell values based a condition or criteria, there a multiple built-in Conditional Formatting tools you can use or use a custom-made conditional formatting formula.
Lets you quickly summarize vast amounts of data in a very user-friendly way. This powerful Excel feature lets you then analyze, organize and categorize important data efficiently.
VBA stands for Visual Basic for Applications and is a computer programming language developed by Microsoft, it allows you to automate time-consuming tasks and create custom functions.
A program or subroutine built in VBA that anyone can create. Use the macro-recorder to quickly create your own VBA macros.
UDF stands for User Defined Functions and is custom built functions anyone can create.
A list of all published articles.
Содержание
- VBA Open / Close Workbook
- Open a Workbook in VBA
- Open Workbook From Path
- Open Workbook – ActiveWorkbook
- Open Workbook and Assign to a Variable
- Workbook Open File Dialog
- Open New Workbook
- VBA Coding Made Easy
- Open New Workbook To Variable
- Open Workbook Syntax
- Open Workbook Read-Only
- Open Password Protected Workbook
- Open Workbook Syntax Notes
- Close a Workbook in VBA
- Close Specific Workbook
- Close Active Workbook
- Close All Open Workbooks
- Close First Opened Workbook
- Close Without Saving
- Save and Close Without Prompt
- Other Workbook Open Examples
- Open Multiple New Workbooks
- Open All Excel Workbooks in a Folder
- Check if a Workbook is Open
- Workbook_Open Event
- Open Other Types of Files in VBA
- Open a Text file and Read its Contents
- Open a Text File and Append to it
- Opening a Word File and Writing to it
- VBA Code Examples Add-in
- VBA List all Open Workbooks in Excel
- Syntax to List Workbooks in Excel VBA
- VBA Code to List all Workbooks in Excel VBA
- Instructions to Run VBA Macro Code or Procedure:
- Other Useful Resources:
- Leave a Reply Cancel reply
- VBA Projects with Source Code
- Help Desk Management System
- Ultimate TOC Builder
- Effortlessly Manage Your Projects
- 120+ Project Management Templates
- Recent Posts
- VBA Projects with Source Code
- Help Desk Management System
- Ultimate TOC Builder
- Vba excel all opened
- Macro code
- How to copy the macro to your workbook
- How to run the macro
- Vba excel all opened
- 3 Tips to Save and Close All Open Excel Workbook Files + Macro
- Tip #1: Shift + Close Window Button
- Tip #2: Add the Close All Button to the Quick Access Toolbar
- Tip #3: Close All Open Workbooks with a Macro
- Macro to Close All Workbooks Without Saving
- How does this macro work?
- Macro to Save All Except New Unsaved Workbooks (Scratch Pads)
- How does this macro work?
- Macro to Save and Close All Workbook and Automatically Name Files
- How does this macro work?
- Free Webinar on Getting Started with Macros & VBA
- What Are Your Tips for Savings & Closing Files?
VBA Open / Close Workbook
In this Article
In this tutorial, you will learn how to use VBA to open and close Excel Workbooks and other types of Files in several ways.
VBA allows you to open or close files using the standard methods .Open and .Close.
If you want to learn how to check if a file exists before attempting to open the file, you can click on this link: VBA File Exists
Open a Workbook in VBA
Open Workbook From Path
If you know which file you want to open, you can specify its full path name in the function. Here is the code:
This line of the code opens “Sample file 1” file from the “VBA Folder”.
Open Workbook – ActiveWorkbook
When you open a workbook, it automatically becomes the ActiveWorkbook. You can reference the newly opened workbook like so:
When you reference a sheet or range and omit the workbook name, VBA will assume you are referring to the ActiveWorkbook:
Open Workbook and Assign to a Variable
You can also open a workbook and assign it directly to an object variable. This procedure will open a workbook to the wb variable and then save the workbook.
Assigning workbooks to variables when they open is the best way to keep track of your workbooks
Workbook Open File Dialog
You can also trigger the workbook Open File Dialog box. This allows the user to navigate to a file and open it:
As you can see in Image 1, with this approach users can choose which file to open. The Open File Dialog Box can be heavily customized. You can default to a certain folder, choose which types of files are visible (ex. .xlsx only), and more. Read our tutorial on the Open File Dialog Box for detailed examples.
Open New Workbook
This line of code will open a new workbook:
VBA Coding Made Easy
Stop searching for VBA code online. Learn more about AutoMacro — A VBA Code Builder that allows beginners to code procedures from scratch with minimal coding knowledge and with many time-saving features for all users!
Open New Workbook To Variable
This procedure will open a new workbook, assigning it to variable wb:
Open Workbook Syntax
When you use Workbooks.Open you might notice that there are many options available when opening the workbook:
The Filename is required. All other arguments are optional – and you probably won’t need to know most of the other arguments. Here are the two most common:
Open Workbook Read-Only
When workbook is opened read-only, you can’t save over the original file. This prevents the file from being edited by the user.
Open Password Protected Workbook
A workbook might be password-protected. Use this code to open the password-protected workbook:
Open Workbook Syntax Notes
Notice that in the image above, we included a parenthesis “(” to show the syntax. If you use parenthesis when working with Workbooks.Open, you must assign the workbook to a variable:
Close a Workbook in VBA
Close Specific Workbook
Similarly to opening a workbook, there are several ways to close a file. If you know which file you want to close, you can use the following code:
This line of code closes the file “Sample file 1” if it’s opened. If not, it will return an error, so you should take care of error handling.
Close Active Workbook
If you want to close the Workbook which is currently active, this line of code will enable you to do that:
Close All Open Workbooks
To close all open Workbooks, you can simply use this code:
Close First Opened Workbook
This will close the first opened/created workbook:
Replace 1 with 2 to close the second opened / created workbook and so on.
Close Without Saving
This will close a Workbook without saving and without showing the save prompt:
Save and Close Without Prompt
Similarly this will save and close a Workbook without showing the save prompt:
Note: There are several other ways to indicate whether to save or not save a Workbook and also whether to show prompts or not. This is discussed in more detail here.
Other Workbook Open Examples
Open Multiple New Workbooks
This procedure will open multiple new workbooks, assigning the new workbooks to an array:
Open All Excel Workbooks in a Folder
This procedure will open all Excel Workbooks in a folder, using the Open File Dialog picker.
Check if a Workbook is Open
Workbook_Open Event
VBA Events are “triggers” that tell VBA to run certain code. You can set up workbook events for open, close, before save, after save and more.
Read our Workbook_Open Event tutorial to learn more about automatically running macros when a workbook is opened.
Open Other Types of Files in VBA
You can use the VBA to open other types of files with VBA – such as txt or Word files.
Open a Text file and Read its Contents
The VBA open method allows you to read or write to the file once you have opened it. To read the contents of a file, we can open the file for INPUT.
The code above will open the text file “test.txt” and then it will read the entire contents of the file to the strBody variable. Once you have extracted the file data into the strBody variable, you can use it for what you require. Using the Debug.Print command above enables us to see the contents of the strBody variable in the Immediate window in the VBE.
Open a Text File and Append to it
We can also open a text file in VBA, and then append to the bottom of the file using the Append method.
The above code will open the text file and then append 2 lines of text to the bottom of the file using the #intFile variable (the # sign is the key!). The code then closes the file.
Opening a Word File and Writing to it
We can also use VBA in Excel to open a Word file.
This code will open a copy of Word, and then open the document test.docx.
VBA Code Examples Add-in
Easily access all of the code examples found on our site.
Simply navigate to the menu, click, and the code will be inserted directly into your module. .xlam add-in.
Источник
VBA List all Open Workbooks in Excel
VBA List all Open Workbooks in Excel. It helps to know all open workbooks name. It is easy to handle and shift between workbooks. We have an option to open multiple workbooks in MS Office Excel. Let us see in the following tutorial how to list open Workbooks in Excel VBA.
Syntax to List Workbooks in Excel VBA
Here is the following syntax to List all Open Workbooks in Excel VBA.
Where Workbook: It represents Workbook object which is part of workbooks collection.
VBA Code to List all Workbooks in Excel VBA
Let us see the following example macro to List all Open Workbooks in Excel VBA
Instructions to Run VBA Macro Code or Procedure:
You can refer the following link for the step by step instructions.
Other Useful Resources:
Click on the following links of the useful resources. These helps to learn and gain more knowledge.
Leave a Reply Cancel reply
You must be logged in to post a comment.
VBA Projects with Source Code
Help Desk Management System
Help Desk Management System is an Excel VBA Project with Full Source Code, realtime VBA Project to Manage Help desk Tickets. Explore the Code and Professional VBA Applications.
Ultimate TOC Builder
Ultimate TOC Builder is Excel VBA Project with Source Code. Real-time VBA Project to Create TOC. Explore the Code to Build Professional VBA Applications.
Effortlessly Manage Your Projects
120+ Project Management Templates
Seamlessly manage your projects with our powerful & multi-purpose templates for project management.
Check our 120+ PM Templates :
Recent Posts
VBA Projects with Source Code
Help Desk Management System
Help Desk Management System is an Excel VBA Project with Full Source Code, realtime VBA Project to Manage Help desk Tickets. Explore the Code and Professional VBA Applications.
Ultimate TOC Builder
Ultimate TOC Builder is Excel VBA Project with Source Code. Real-time VBA Project to Create TOC. Explore the Code to Build Professional VBA Applications.
Источник
Vba excel all opened
In this post, I am going to demonstrate how to automatically create a new sheet in the current workbook and list all open workbooks and their sheets using a VBA macro.
The image above shows the new worksheet, it contains the names of the workbooks and corresponding worksheets I have currently open.
Macro code
How to copy the macro to your workbook
- Press Alt+F11 to open the VB Editor.
- Press with right mouse button on on your workbook in the Project Explorer.
- Press with left mouse button on «Insert» and then «Module».
- Copy macro code.
- Press with left mouse button on in code module window to see the input prompt.
- Paste code to code module.
- Return to Excel.
How to run the macro
- Go to «Developer» tab on the ribbon.
- Press with left mouse button on «Macros» button.
- Select «ListWorkbooks» macro.
- Press with left mouse button on «Run» button.
Источник
Vba excel all opened
I got some problem in finding the names of all excel opened files using word VBA.
Following code is working in excel vba but i am not able to do it in word vba. Can some one help me. Thanks in advance.
Dim wb As Workbook
For Each wb In Application.Workbooks
MsgBox wb.Name
Next
Try something along the lines of:
Finally i am able to manage instanse create object and able to retrieve the names of all active excel file names.
I know this one is solved, but I didn’t want to start a whole new thread for the same issue (pretty close).
I used the code above with a tweak to populate a listbox, but it is only picking up 1 open excel file. it is not doing each.
here is my code:
No way! Thank you for the quick response macropod! you’re the best!
If I have multiple excel docs open, only 1 shows up in my list. I have to close the other docs and reopen the user form in order to get to the one I want.
any ideas if I am running a setting wrong? I have the Excel 14.0 library reference included already.
Источник
3 Tips to Save and Close All Open Excel Workbook Files + Macro
Bottom line: Learn a few shortcuts and tips to save and close all open Excel workbooks.
Skill level: Beginner
If you use Excel all day every day like I do, then it can be easy to have a lot of workbooks open at the same time. I try to stay disciplined with this, but sometimes it’s hard. And at the end of the day, we just want to close all open workbooks and go home! So this post contains a few tips for quickly closing all open files to help beat rush hour traffic. 🙂
Tip #1: Shift + Close Window Button
The quickest way to close all open workbooks is to hold the Shift key while pressing the Close Window button. The Close Window button is the “x” in the top-right corner of the application window.
If all of the open workbooks have been saved, then they will all be closed.
If any of the open workbooks have NOT been saved, then you will be prompted to save the file. The pop-up window will appear and you will have to press Save or Don’t Save for each unsaved workbook.
The window also contains a Save All button. You can press this to Save All the unsaved workbooks in one step.
Clicking the Cancel button will cancel the entire operation and the wordbooks that are still open will remain open.
But what if we don’t want to save all or some of the open workbooks? We’ll get to that in tip #3.
Tip #2: Add the Close All Button to the Quick Access Toolbar
We can also add the Close All button to the Quick Access Toolbar (QAT) to close all open workbooks. This does the same thing as the Shift+Close Window shortcut.
The advantage here is that we can use a keyboard shortcut to press the button. The QAT buttons can be accessed with a keyboard shortcut by pressing the Alt Key and the number assigned to the button.
To add the Close All button to the QAT, open the Excel Options window (File>Options) and follow the steps on the image below.
After pressing the Close All button we will be prompted with the same window as described in tip #1.
Bonus Tip: We can also use the keyboard shortcut Ctrl+W to close a single workbook. I mentioned this tip in my post on 17 Excel shortcuts for 2017.
Tip #3: Close All Open Workbooks with a Macro
In this section I will share a few macros that can be used to close all open workbooks. The macros give us a lot more flexibility when we want to control which workbooks are saved before closing.
You can download the Excel file that contains the macros here.
Macro to Close All Workbooks Without Saving
If we don’t want to save any of the open files, then we can use the following macro.
How does this macro work?
The macro above loops through all of the open workbooks on the computer using a For Next Loop. It uses an If statement to check if the file in the loop (wb.Name) is NOT (<>) the file that contains the code ThisWorkbook.Name.
It then uses the Workbooks.Close method (MSDN Help Page) to close the workbook. The Close method has an optional parameter to SaveChanges. We can set this to True to save changes, and False to close without saving.
Note: This macro should only be run if you are certain you don’t want to save changes to any of the open files. There is no way to undo this. You might also want to add a Yes/No Message Box prompt to warn the user before running this macro.
Macro to Save All Except New Unsaved Workbooks (Scratch Pads)
At the end of my workday I usually have a combination of some workbooks that I want to save, and some that I do NOT want to save. I often open new workbooks to use the Excel files for quick calculations. I call these “scratch pads”. I don’t necessarily want to save these, but I might want to save all other open files.
The scratch pad files have never been saved, so they don’t have a file extension yet. They are named: Book1, Book2, Book2, etc. Notice in the screenshot that there is no file extension (.xlsx, .xlsm).
So we can add an If statement to our macro to see if a file extension exists. If the file extension exists, then we will save the file. If not, then we will close without saving.
How does this macro work?
This macro is similar to the macro to close all workbooks. The difference is we use an If statement to test if the file has an extension.
The Right function is used to return the 5 characters at the end of the file name. If wb is an existing file that has already been saved, then Right(wb.Name, 5) will return “.xlsx” or “.xlsm”.
The Instr function (MSDN Help Page) is used to find a string within a string. It returns the starting character number of the string. So, if Instr finds “.xls” within “.xlsx” or “.xlsm”, it will return 1. Otherwise, it will return a 0.
The If statement checks if the return value from Instr is greater than 0, and saves changes while closing the workbook. Otherwise, changes are not saved for workbooks that do NOT contain an extension.
Macro to Save and Close All Workbook and Automatically Name Files
Sometimes we might want to save some of those new files (scratch pads), but don’t have time to go through each file and save it with a name. This is like hitting the Excel eject button when we don’t want to lose any of our work.
The following macro will save and close ALL files, and automatically name the new files that have not been saved. It puts all the new (scratch pad) files in a folder that you specify.
You can then go back to that folder when you have some free time to move and rename the files.
How does this macro work?
This macro works similar to the other two above. The only difference is that it saves the new files (scratch pads) to a folder on your computer.
To use this macro you will need to change the sPath variable to a folder on you computer. Make sure to end the file path string with a back slash.
The Workbooks.Close method has another optional parameter (Filename) that allows us to specify a file name where we want to save the file, if the file has NOT been saved yet.
If we do not use the Filename parameter, then Excel will prompt us with the Save As menu for each file. So, specifying the Filename bypasses this window and can save us a lot of time.
The value of the Filename parameter is concatenating the string for the full file path. It is also amending the current date and time to the end of the file name using the Format and Now functions. The Format function in VBA is similar to the TEXT function in Excel, and allows us to specify a number format. The Now function returns the current date and time on the user’s computer.
I recommend adding these macros to your Personal Macro Workbook so you can use them anytime. Checkout my article and video series on the personal macro workbook to learn more.
Free Webinar on Getting Started with Macros & VBA
If you are interested in learning more about macros, I’m currently running my free webinar called “The 7 Steps to Getting Started with Macros & VBA”. It’s running all this week, and it’s absolutely free to register.
During the webinar I explain why you might want to learn VBA, and a lot of the basic coding concepts that will help you get started. I jump into Excel and the VB Editor and walk through how to write and run our first macro. Even if you have been using VBA for awhile, I’m sure you will learn some new tips.
What Are Your Tips for Savings & Closing Files?
I hope those tips and macros help you end the day a little quicker. Do you have any other tips for closing files. Please leave a comment below with any suggestions or questions. Thank you!
Источник
I think I found all the declares for the two functions. This give output like this
Order Level WindowText ClassName HWnd ParentHWnd ProcessID ParentProcessID ThreadID ModuleNameHWin EXENameProcess
1 0 MSCTFIME UI MSCTFIME UI 16253876 16253876 3288 6640 7404 C:UsersDavid CandyDesktopEditorEditorSdiEd.exe explorer.exe
2 0 Default IME IME 9503286 16253876 3288 6640 7404 «Not Available Error=126» explorer.exe
It expects to find a textedit control to write to.
Public Declare Function GetClassName Lib "user32" Alias "GetClassNameA" (ByVal hwnd As Long, ByVal lpClassName As String, ByVal nMaxCount As Long) As Long
Public Declare Function GetDC Lib "user32" (ByVal hwnd As Long) As Long
Public Declare Function GetMapMode Lib "gdi32" (ByVal hdc As Long) As Long
Public Declare Function GetStdHandle Lib "kernel32" (ByVal nStdHandle As Long) As Long
Public Declare Function GetStringTypeEx Lib "kernel32" Alias "GetStringTypeExA" (ByVal Locale As Long, ByVal dwInfoType As Long, ByVal lpSrcStr As String, ByVal cchSrc As Long, ByRef lpCharType As Integer) As Long
Public Declare Function GetSysColor Lib "user32" (ByVal nIndex As Long) As Long
Public Declare Function GetTempFileName Lib "kernel32" Alias "GetTempFileNameA" (ByVal lpszPath As String, ByVal lpPrefixString As String, ByVal wUnique As Long, ByVal lpTempFileName As String) As Long
Public Declare Function GetTempPath Lib "kernel32" Alias "GetTempPathA" (ByVal nBufferLength As Long, ByVal lpBuffer As String) As Long
Public Declare Function GetTopWindow Lib "user32" (ByVal hwnd As Long) As Long
Public Declare Function GetWindow Lib "user32" (ByVal hwnd As Long, ByVal wCmd As Long) As Long
Public Declare Function GetWindowModuleFileName Lib "user32" Alias "GetWindowModuleFileNameA" (ByVal hwnd As Long, ByVal WinModule As String, StringLength As Long) As Long
Public Declare Function GetWindowRect Lib "user32" (ByVal hwnd As Long, lpRect As RECT) As Long
Public Declare Function GetWindowText Lib "user32" Alias "GetWindowTextA" (ByVal hwnd As Long, ByVal lpString As String, ByVal cch As Long) As Long
Public Declare Function GetWindowThreadProcessId Lib "user32" (ByVal hwnd As Long, lpdwProcessId As Long) As Long
Private Declare Function Process32Next Lib "kernel32" (ByVal hSnapshot As Long, lppe As PROCESSENTRY32) As Long
Private Declare Function CloseHandle Lib "Kernel32.dll" (ByVal Handle As Long) As Long
Private Declare Function Process32First Lib "kernel32" (ByVal hSnapshot As Long, lppe As PROCESSENTRY32) As Long
Private Declare Function CreateToolhelp32Snapshot Lib "kernel32" (ByVal dwFlags As Long, ByVal th32ProcessID As Long) As Long
Private Declare Function GetVersionExA Lib "kernel32" _
(lpVersionInformation As OSVERSIONINFO) As Integer
Private Type PROCESSENTRY32
dwSize As Long
cntUsage As Long
th32ProcessID As Long ' This process
th32DefaultHeapID As Long
th32ModuleID As Long ' Associated exe
cntThreads As Long
th32ParentProcessID As Long ' This process's parent process
pcPriClassBase As Long ' Base priority of process threads
dwFlags As Long
szExeFile As String * 260 ' MAX_PATH
End Type
Private Type OSVERSIONINFO
dwOSVersionInfoSize As Long
dwMajorVersion As Long
dwMinorVersion As Long
dwBuildNumber As Long
dwPlatformId As Long '1 = Windows 95 2 = Windows NT
szCSDVersion As String * 128
End Type
Private Const PROCESS_QUERY_INFORMATION = 1024
Private Const PROCESS_VM_READ = 16
Private Const MAX_PATH = 260
Private Const STANDARD_RIGHTS_REQUIRED = &HF0000
Private Const SYNCHRONIZE = &H100000
'STANDARD_RIGHTS_REQUIRED Or SYNCHRONIZE Or &HFFF
Private Const PROCESS_ALL_ACCESS = &H1F0FFF
Private Const TH32CS_SNAPPROCESS = &H2&
Private Const hNull = 0
Private Const GW_CHILD = 5
Private Const GW_HWNDNEXT = 2
Private Type GUID
Data1 As Long
Data2 As Integer
Data3 As Integer
Data4(7) As Byte
End Type
Private Declare Function GetUserName Lib "advapi32.dll" Alias "GetUserNameA" (ByVal lpBuffer As String, nSize As Long) As Long
Private Declare Function IsWindowUnicode Lib "user32" (ByVal hwnd As Long) As Boolean
Private Declare Function OSWinHelp% Lib "user32" Alias "WinHelpA" (ByVal hwnd&, ByVal HelpFile$, ByVal wCommand%, dwData As Any)
Private Declare Function CoCreateGuid Lib "OLE32.DLL" (pGuid As GUID) As Long
Sub mnuInsertWindowList_Click()
' WindowChain = 0
Dim hwnd As Long
hwnd = GetTopWindow(0)
If hwnd <> 0 Then
AddChildWindows hwnd, 0
End If
End Sub
Private Function AddChildWindows(ByVal hwndParent As Long, ByVal Level As Long) As String
Dim gwfnhwnd As Long, X As Long, WT As String, CN As String, Length As Long, hwnd As Long, TID As Long, PID As Long, MN As String, Ret As Long, Parenthwnd As Long
Static Order As Long
Static FirstTime As Long
Parenthwnd = hwndParent
If Level = 0 Then
hwnd = hwndParent
Else
hwnd = GetWindow(hwndParent, GW_CHILD)
End If
Do While hwnd <> 0
WT = Space(512)
Length = GetWindowText(hwnd, WT, 508)
WT = Left$(WT, Length)
If WT = "" Then WT = Chr(171) & "No Window Text " & Err.LastDllError & Chr(187)
CN = Space(512)
Length = GetClassName(hwnd, CN, 508)
CN = Left$(CN, Length)
If CN = "" Then CN = "Error=" & Err.LastDllError
TID = GetWindowThreadProcessId(hwnd, PID)
MN = Space(512)
Length = GetWindowModuleFileName(hwnd, MN, 508)
If Length = 0 Then
MN = Chr(171) & "Not Available Error=" & Err.LastDllError & Chr(187)
Else
MN = Left$(MN, Length)
End If
Dim f As Long, sname As String, PList As String, PPID As Long
Dim hSnap As Long, proc As PROCESSENTRY32, Temp As String
hSnap = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0)
If hSnap = hNull Then Exit Function
proc.dwSize = LenB(proc)
' Iterate through the processes
f = Process32First(hSnap, proc)
Do
If PID = proc.th32ProcessID Then
sname = StrZToStr(proc.szExeFile)
PPID = proc.th32ParentProcessID
End If
f = Process32Next(hSnap, proc)
Loop While f = 1
Order = Order + 1
' CStr(Order) & " HWnd=" & FormatNumber$(hwnd, 0, vbFalse, vbFalse, vbFalse) & " Parent HWnd=" & FormatNumber$(Parenthwnd, 0, vbFalse, vbFalse, vbFalse) & " Level=" & CStr(Level) & WT & " (" & CN & ")" & " PID=" & FormatNumber$(PID, 0, vbFalse, vbFalse, vbFalse) & " TID=" & FormatNumber$(TID, 0, vbFalse, vbFalse, vbFalse) & " Module Name:" & MN & " ExeName:" & sname & vbCrLf
If FirstTime = 0 Then
txtNote.SelText = vbCrLf & "Order" & vbTab & "Level" & vbTab & "WindowText" & vbTab & "ClassName" & vbTab & "HWnd" & vbTab & "ParentHWnd" & vbTab & "ProcessID" & vbTab & "ParentProcessID" & vbTab & "ThreadID" & vbTab & "ModuleNameHWin" & vbTab & "EXENameProcess"
FirstTime = 1
End If
txtNote.SelText = vbCrLf & CStr(Order) & vbTab & CStr(Level) & vbTab & WT & vbTab & CN & vbTab & CStr(hwnd) & vbTab & CStr(Parenthwnd) & vbTab & CStr(PID) & vbTab & CStr(PPID) & vbTab & CStr(TID) & vbTab & MN & vbTab & sname
AddChildWindows hwnd, Level + 1
hwnd = GetWindow(hwnd, GW_HWNDNEXT)
Loop
End Function
What This VBA Code Does
This bit of VBA code shows you how to loop through all currently open Excel workbooks and make a modification to them. In the example code below today’s date is added to the first worksheet in Cell A1. Notice also that the loop will skip a Personal Macro workbook if one is created.
Using VBA Code Found On The Internet
Now that you’ve found some VBA code that could potentially solve your Excel automation problem, what do you do with it? If you don’t necessarily want to learn how to code VBA and are just looking for the fastest way to implement this code into your spreadsheet, I wrote an article (with video) that explains how to get the VBA code you’ve found running on your spreadsheet.
Getting Started Automating Excel
Are you new to VBA and not sure where to begin? Check out my quickstart guide to learning VBA. This article won’t overwhelm you with fancy coding jargon, as it provides you with a simplistic and straightforward approach to the basic things I wish I knew when trying to teach myself how to automate tasks in Excel with VBA Macros.
Also, if you haven’t checked out Excel’s latest automation feature called Power Query, I have put together a beginner’s guide for automating with Excel’s Power Query feature as well! This little-known built-in Excel feature allows you to merge and clean data automatically with little to no coding!
How Do I Modify This To Fit My Specific Needs?
Chances are this post did not give you the exact answer you were looking for. We all have different situations and it’s impossible to account for every particular need one might have. That’s why I want to share with you: My Guide to Getting the Solution to your Problems FAST! In this article, I explain the best strategies I have come up with over the years to get quick answers to complex problems in Excel, PowerPoint, VBA, you name it!
I highly recommend that you check this guide out before asking me or anyone else in the comments section to solve your specific problem. I can guarantee that 9 times out of 10, one of my strategies will get you the answer(s) you are needing faster than it will take me to get back to you with a possible solution. I try my best to help everyone out, but sometimes I don’t have time to fit everyone’s questions in (there never seem to be quite enough hours in the day!).
I wish you the best of luck and I hope this tutorial gets you heading in the right direction!
Chris
Founder, TheSpreadsheetGuru.com