Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can ActiveSheet, ActiveWorkbook or ThisWorkbook be set as the default for an optional parameter in VBA?

I am trying to set the default value of an optional parameter to Excel's Application.ActiveWorkbook property. Here is my failed attempt:

Attempted Code

Function SheetExists(ByVal sheetName As String, _
    Optional ByVal targetBook As Workbook = Application.ActiveWorkbook) As Boolean

Result

This code caused a

Constant expression required : compile error

Questions

  1. What is a "Constant Expression"?
  2. Is there another way to use the ActiveWorkbook property (and other properties) as default values of parameters in functions and subroutines?
like image 639
ChrisB Avatar asked Sep 01 '25 20:09

ChrisB


1 Answers

Can you use something like this:

Public function SheetExists(ByVal sheetName As String, Optional wb As Workbook)

  If wb Is Nothing Then Set wb =  Application.ActiveWorkbook 'or ThisWorkbook

  'your code here, for example
  wb.Application.Calculation = xlAutomatic 
End Sub

Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!