Friday, December 25, 2015

Workbook Open Check in VBA

Below code use to check a workbook is open or not?


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
Sub Sample01()
    Dim wb As Workbook, flag As Boolean
    For Each wb In Workbooks
        If wb.Name = "Book1.xlsm" Then flag = True
    Next wb
    If flag = True Then
        MsgBox "Book1 Open", vbInformation
    Else
        MsgBox "Book1 Not Open", vbInformation
    End If
End Sub

Above code  if Workbook name is BOOK1.xlsm


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
Sub Sample02()
    Dim wb As Workbook, flag As Boolean
    For Each wb In Workbooks
        If wb.Name = "BOOK1.xlsm" Then flag = True
    Next wb
    If flag = True Then
        MsgBox "Book1 Open", vbInformation
    Else
        MsgBox "Book1 Not Open", vbInformation
    End If
End Sub

But, that problem can solve easily with use UCASE or LCASE function.
UCASE function -> change string to Upper Case
LCASE function -> change string to Lower Case


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
Sub Sample03()
    Dim wb As Workbook, flag As Boolean
    For Each wb In Workbooks
        If UCase(wb.Name) = "BOOK1.XLSM" Then flag = True
    Next wb
    If flag = True Then
        MsgBox "Book1 Open", vbInformation
    Else
        MsgBox "Book1 Not Open", vbInformation
    End If
End Sub


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
Sub Sample04()
    Dim wb As Workbook, flag As Boolean
    For Each wb In Workbooks
        If LCase(wb.Name) = "book1.xlsm" Then flag = True
    Next wb
    If flag = True Then
        MsgBox "Book1 Open", vbInformation
    Else
        MsgBox "Book1 Not Open", vbInformation
    End If
End Sub

Download File



No comments :

Post a Comment