What is the syntax to retrieve all open workbooks in Excel?

'wb.Name holds the name of the open workbook
Dim wb As Workbook
For Each wb In Application.Workbooks
 <code here with involving wb.Name>
Next wb
'example
Dim wb As Workbook
For Each wb In Application.Workbooks 'for each open workbook, pass the name to lookupEGA()
   MsgBox wb.Name
   lstWorkbooks.AddItem wb.Name
Next wb

 

Advertisements

What is the syntax to replace a value in a whole workbook?

Dim Sht As Worksheet
For Each Sht In Worksheets
   Sht.Cells.Replace What:=<old value>, Replacement:=<new value>, LookAt:=xlPart, MatchCase:=False
Next
'example - replaces all instances of person's name
'Old first/last name are in A1, B2 (respectively) in Sheet "Names"
Dim Sht As Worksheet
For Each Sht In Worksheets
    Sht.Cells.Replace What:=Sheets("MasterNames").Cells(1, 1).Value, Replacement:=txtNameFirst.Value, LookAt:=xlPart, MatchCase:=False
    Sht.Cells.Replace What:=Sheets("MasterNames").Cells(1, 2).Value, Replacement:=txtNameLast.Value, LookAt:=xlPart, MatchCase:=False
Next

 

 

What is the syntax to close a workbook?

ActiveWorkbook.Close SaveChanges:=<true/false>
#true if want to save changes before closing
#false if disregard changes before closing
#example
Private Sub btnExit_Click()
   ActiveWorkbook.Close SaveChanges:=True 
End Sub

 

 

Tips for debugging when working with workbooks

When working with workbooks, you may get Run-Time Error:9. That is, the following message box may pop up during execution:

Capture.PNG

Tips for debugging this error:

  • Is the workbook you are referencing currently closed?
  • Did you misspell the name of the workbook?
  • Are you trying to reference a new workbook that has not been explicitly saved for the first time?
  • Are you running two instances of Excel?
  • Did you pass an index that is greater than the number of workbooks open?

What is the syntax to write to another workbook?

'to retrieve data
Workbooks("<workbook file name>").Worksheets("<sheet name>").Range("<your range>").Value
Workbooks("<workbook file name>").Worksheets("<sheet name>").Cells(<row number>, <column number>).Value

'to set data
Workbooks("<workbook file name>").Workbooks("Worksheets("<sheet name>").Range("<your range>") = <your value/data>
Workbooks("<workbook file name>").Worksheets("<sheet name>").Cells(<row number>, <column number>).Value = <your value/data>
'examples
Workbooks("example.xlsm").Worksheets("Example").Range("A1:A4") = "hello"
Workbooks("book3.xlsx").Worksheets("Example").Range("D1") = "world"
Workbooks("book3.xlsx").Worksheets("Example").Cells(2, 4).Value = "goodbye"