Excel check file open

In VBA, I opened an MS Excel file named «myWork.XL» programmatically.

Now I would like a code that can tell me about its status — whether it is open or not. I.e. something like IsWorkBookOpened("myWork.XL) ?

Andrei Konstantinov's user avatar

asked Feb 21, 2012 at 6:19

user1222679's user avatar

0

Try this:

Option Explicit

Sub Sample()
    Dim Ret

    Ret = IsWorkBookOpen("C:myWork.xlsx")

    If Ret = True Then
        MsgBox "File is open"
    Else
        MsgBox "File is Closed"
    End If
End Sub

Function IsWorkBookOpen(FileName As String)
    Dim ff As Long, ErrNo As Long

    On Error Resume Next
    ff = FreeFile()
    Open FileName For Input Lock Read As #ff
    Close ff
    ErrNo = Err
    On Error GoTo 0

    Select Case ErrNo
    Case 0:    IsWorkBookOpen = False
    Case 70:   IsWorkBookOpen = True
    Case Else: Error ErrNo
    End Select
End Function

Tim Cooper's user avatar

Tim Cooper

156k38 gold badges330 silver badges278 bronze badges

answered Feb 21, 2012 at 7:48

Siddharth Rout's user avatar

Siddharth RoutSiddharth Rout

146k17 gold badges206 silver badges250 bronze badges

12

For my applications, I generally want to work with a workbook rather than just determine if it’s open. For that case, I prefer to skip the Boolean function and just return the workbook.

Sub test()

    Dim wb As Workbook

    Set wb = GetWorkbook("C:UsersdickDropboxExcelHoops.xls")

    If Not wb Is Nothing Then
        Debug.Print wb.Name
    End If

End Sub

Public Function GetWorkbook(ByVal sFullName As String) As Workbook

    Dim sFile As String
    Dim wbReturn As Workbook

    sFile = Dir(sFullName)

    On Error Resume Next
        Set wbReturn = Workbooks(sFile)

        If wbReturn Is Nothing Then
            Set wbReturn = Workbooks.Open(sFullName)
        End If
    On Error GoTo 0

    Set GetWorkbook = wbReturn

End Function

answered Feb 21, 2012 at 17:18

Dick Kusleika's user avatar

Dick KusleikaDick Kusleika

32.5k4 gold badges51 silver badges73 bronze badges

6

If its open it will be in the Workbooks collection:

Function BookOpen(strBookName As String) As Boolean
    Dim oBk As Workbook
    On Error Resume Next
    Set oBk = Workbooks(strBookName)
    On Error GoTo 0
    If oBk Is Nothing Then
        BookOpen = False
    Else
        BookOpen = True
    End If
End Function

Sub testbook()
    Dim strBookName As String
    strBookName = "myWork.xls"
    If BookOpen(strBookName) Then
        MsgBox strBookName & " is open", vbOKOnly + vbInformation
    Else
        MsgBox strBookName & " is NOT open", vbOKOnly + vbExclamation
    End If
End Sub

answered Feb 21, 2012 at 8:44

Charles Williams's user avatar

Charles WilliamsCharles Williams

23.1k5 gold badges37 silver badges38 bronze badges

2

I would go with this:

Public Function FileInUse(sFileName) As Boolean
    On Error Resume Next
    Open sFileName For Binary Access Read Lock Read As #1
    Close #1
    FileInUse = IIf(Err.Number > 0, True, False)
    On Error GoTo 0
End Function

as sFileName you have to provide direct path to the file for example:

Sub Test_Sub()
    myFilePath = "C:UsersUserNameDesktopexample.xlsx"
    If FileInUse(myFilePath) Then
        MsgBox "File is Opened"
    Else
        MsgBox "File is Closed"
    End If
End Sub

answered Mar 10, 2014 at 19:39

user2267971's user avatar

user2267971user2267971

3631 gold badge4 silver badges12 bronze badges

What if you want to check without creating another Excel instance?

For example, I have a Word macro (which is run repeatedly) that needs to extract data from an Excel spreadsheet. If the spreadsheet is already open in an existing Excel instance, I would prefer not to create a new instance.

I found a great answer here that I built on:
http://www.dbforums.com/microsoft-access/1022678-how-check-wether-excel-workbook-already-open-not-search-value.html

Thanks to MikeTheBike and kirankarnati

Function WorkbookOpen(strWorkBookName As String) As Boolean
    'Returns TRUE if the workbook is open
    Dim oXL As Excel.Application
    Dim oBk As Workbook

    On Error Resume Next
    Set oXL = GetObject(, "Excel.Application")
    If Err.Number <> 0 Then
        'Excel is NOT open, so the workbook cannot be open
        Err.Clear
        WorkbookOpen = False
    Else
        'Excel is open, check if workbook is open
        Set oBk = oXL.Workbooks(strWorkBookName)
        If oBk Is Nothing Then
            WorkbookOpen = False
        Else
            WorkbookOpen = True
            Set oBk = Nothing
        End If
    End If
    Set oXL = Nothing
End Function

Sub testWorkbookOpen()
    Dim strBookName As String
    strBookName = "myWork.xls"
    If WorkbookOpen(strBookName) Then
        msgbox strBookName & " is open", vbOKOnly + vbInformation
    Else
        msgbox strBookName & " is NOT open", vbOKOnly + vbExclamation
    End If
End Sub

answered Aug 9, 2013 at 7:19

Derek Johnson's user avatar

Derek JohnsonDerek Johnson

9271 gold badge11 silver badges15 bronze badges

This one is a bit easier to understand:

Dim location As String
Dim wbk As Workbook

location = "c:excel.xls"

Set wbk = Workbooks.Open(location)

'Check to see if file is already open
If wbk.ReadOnly Then
  ActiveWorkbook.Close
    MsgBox "Cannot update the excelsheet, someone currently using file. Please try again later."
    Exit Sub
End If

answered Jul 9, 2013 at 14:26

Bulki's user avatar

BulkiBulki

7341 gold badge10 silver badges30 bronze badges

1

Checkout this function

'********************************************************************************************************************************************************************************
'Function Name                     : IsWorkBookOpen(ByVal OWB As String)
'Function Description             : Function to check whether specified workbook is open
'Data Parameters                  : OWB:- Specify name or path to the workbook. eg: "Book1.xlsx" or "C:UsersKannan.SDesktopBook1.xlsm"

'********************************************************************************************************************************************************************************
Function IsWorkBookOpen(ByVal OWB As String) As Boolean
    IsWorkBookOpen = False
    Dim WB As Excel.Workbook
    Dim WBName As String
    Dim WBPath As String
    Err.Clear
    On Error Resume Next
    OWBArray = Split(OWB, Application.PathSeparator)
    Set WB = Application.Workbooks(OWBArray(UBound(OWBArray)))
    WBName = OWBArray(UBound(OWBArray))
    WBPath = WB.Path & Application.PathSeparator & WBName
    If Not WB Is Nothing Then
        If UBound(OWBArray) > 0 Then
            If LCase(WBPath) = LCase(OWB) Then IsWorkBookOpen = True
        Else
            IsWorkBookOpen = True
        End If
    End If
    Err.Clear
End Function

answered Nov 14, 2013 at 16:33

Kannan Suresh's user avatar

Kannan SureshKannan Suresh

4,5933 gold badges34 silver badges59 bronze badges

5

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

Проверьте, открыта или закрыта книга с помощью VBA

Проверьте, открыта ли книга или закрыта с помощью Kutools for Excel хорошая идея3


Проверьте, открыта или закрыта книга с помощью VBA

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

1. Нажмите Alt + F11 ключи для открытия Microsoft Visual Basic для приложений окно.

2. Нажмите Вставить > Модули а затем скопируйте и вставьте VBA в новый Модули окно.

VBA: проверьте, открыта или закрыта книга

Function IsWorkBookOpen(Name As String) As Boolean
    Dim xWb As Workbook
    On Error Resume Next
    Set xWb = Application.Workbooks.Item(Name)
    IsWorkBookOpen = (Not xWb Is Nothing)
End Function

Sub Sample()
    Dim xRet As Boolean
    xRet = IsWorkBookOpen("combine.xlsx")
    If xRet Then
        MsgBox "The file is open", vbInformation, "Kutools for Excel"
    Else
        MsgBox "The file is not open", vbInformation, "Kutools for Excel"
    End If
End Sub

3. И нажмите F5 нажмите клавишу, чтобы запустить эту vba, и появится диалоговое окно, напоминающее вам, открыта конкретная книга или нет.
док проверить, открыт ли файл 1     док проверить, открыт ли файл 2

Наконечник: В приведенном выше VBA «объединять»- это имя книги, которую вы хотите проверить, вы можете использовать ее по своему усмотрению.


Проверьте, открыта ли книга или закрыта с помощью Kutools for Excel

Если вы не знакомы с VBA, вы можете проверить, открыта ли книга, с помощью Kutools for Excel, с его Навигация панель, которая поможет вам четко просмотреть все открытые книги в списке книг на панели.

После бесплатная установка Kutools for Excel, пожалуйста, сделайте следующее:

1. Нажмите Кутулс > Навигация , чтобы включить панель навигации. Смотрите скриншот:
док проверить, открыт ли файл 3

2. Затем нажмите Рабочая тетрадь и лист кнопку, чтобы развернуть панель и перейти к Рабочая тетрадь и лист раздел. И вы можете просмотреть все открытые книги в верхнем списке. Смотрите скриншот:
док проверить, открыт ли файл 4

Работы С Нами Навигация панели, вы также можете быстро переключаться между книгами или листами в списке.

Щелкните здесь, чтобы узнать больше о навигации.


Лучшие инструменты для работы в офисе

Kutools for Excel Решит большинство ваших проблем и повысит вашу производительность на 80%

  • Снова использовать: Быстро вставить сложные формулы, диаграммы и все, что вы использовали раньше; Зашифровать ячейки с паролем; Создать список рассылки и отправлять электронные письма …
  • Бар Супер Формулы (легко редактировать несколько строк текста и формул); Макет для чтения (легко читать и редактировать большое количество ячеек); Вставить в отфильтрованный диапазон
  • Объединить ячейки / строки / столбцы без потери данных; Разделить содержимое ячеек; Объединить повторяющиеся строки / столбцы… Предотвращение дублирования ячеек; Сравнить диапазоны
  • Выберите Дубликат или Уникальный Ряды; Выбрать пустые строки (все ячейки пустые); Супер находка и нечеткая находка во многих рабочих тетрадях; Случайный выбор …
  • Точная копия Несколько ячеек без изменения ссылки на формулу; Автоматическое создание ссылок на несколько листов; Вставить пули, Флажки и многое другое …
  • Извлечь текст, Добавить текст, Удалить по позиции, Удалить пробел; Создание и печать промежуточных итогов по страницам; Преобразование содержимого ячеек в комментарии
  • Суперфильтр (сохранять и применять схемы фильтров к другим листам); Расширенная сортировка по месяцам / неделям / дням, периодичности и др .; Специальный фильтр жирным, курсивом …
  • Комбинируйте книги и рабочие листы; Объединить таблицы на основе ключевых столбцов; Разделить данные на несколько листов; Пакетное преобразование xls, xlsx и PDF
  • Более 300 мощных функций. Поддерживает Office/Excel 2007-2021 и 365. Поддерживает все языки. Простое развертывание на вашем предприятии или в организации. Полнофункциональная 30-дневная бесплатная пробная версия. 60-дневная гарантия возврата денег.

вкладка kte 201905


Вкладка Office: интерфейс с вкладками в Office и упрощение работы

  • Включение редактирования и чтения с вкладками в Word, Excel, PowerPoint, Издатель, доступ, Visio и проект.
  • Открывайте и создавайте несколько документов на новых вкладках одного окна, а не в новых окнах.
  • Повышает вашу продуктивность на 50% и сокращает количество щелчков мышью на сотни каждый день!

офисный дно

Комментарии (5)


Оценок пока нет. Оцените первым!

Home / VBA / VBA Check IF a Workbook is Open (Excel File)

To check if a workbook is open using a VBA code, you need to use FOR EACH loop that can loop through all the workbooks that are open at the moment and verify each workbook’s name with the name you have mentioned. You can use a message box to get the result of the loop. Or you can also make the code to enter the result in a cell.

  1. First, you need to declare variables to use in the code to create a loop.
    1-create-a-loop
  2. Use an input box to get the name of the workbook that you wish to search for.
    2-use-an-input-box
  3. Start the loop to loop through all the open workbooks.
    3-start-the-loop-to-loop
  4. Write code with IF STATEMENT to verify the name of the workbook with the name you have entered in the input box, and once the name matches, activates the workbook, show a message box that workbook is found, and exit the procedure.
    4-code-with-if-statement
  5. In the end, end the loop and use a message box to show a message box if nothing has been found.
    5-end-the-loop-and-use-amessage-box

Helpful Links: Run a Macro – Macro Recorder – Visual Basic Editor – Personal Macro Workbook

Here’s the full code.

Sub vba_check_workbook()

Dim WB As Workbook
Dim myWB As String

myWB = InputBox(Prompt:="Enter the workbook name.")

For Each WB In Workbooks
    If WB.Name = myWB Then
        WB.Activate
        MsgBox "Workbook Found!"
        Exit Sub
    End If
Next WB

MsgBox "Not Found"

End Sub

More on VBA Workbooks

VBA Save Workbook | VBA Close Workbook | VBA Delete Workbook | VBA ThisWorkbook | VBA Rename Workbook | VBA Activate Workbook | VBA Combine Workbook | VBA Protect Workbook (Unprotect) | VBA Open Workbook | VBA Check IF an Excel Workbook Exists in a Folder| VBA Create New Workbook (Excel File)

  • VBA Workbook

This tutorial shows how to check if a specific workbook is open through the use of VBA

METHOD 1. Check if workbook is open in the same Excel session

VBA

Sub Check_if_workbook_is_open()

‘declare a variable
Dim wb As Workbook

For Each wb In Workbooks

If wb.Name = «Parameters.xlsx» Then

‘this message will appear if one of the open workbooks is Parameters.xlsx
MsgBox «File is Open»

End If

Next

End Sub

ADJUSTABLE PARAMETERS
File Name: Select the file name of a workbook that you want to check if it’s open by changing the file name «Parameters.xlsx» in the VBA code.
Message: Select the message that you want to be displayed if the workbook is open by changing the message «File is Open» in the VBA code.

ADDITIONAL NOTES
Note 1: This VBA code will check Excel workbooks in the same session as the workbook from which you are running this VBA code.

METHOD 2. Check if workbook is open across all Excel sessions

VBA

Sub Check_if_workbook_is_open()

‘declare a variable
Dim FilePath As String

FilePath = IsWBOpen(«C:ExcelParameters.xlsx»)

If FilePath = True Then

MsgBox «File is Open»

Else

MsgBox «File is Closed»

End If

End Sub

Function IsWBOpen(FileName As String)

‘declare variables
Dim FileNo As Long
Dim ErrorNo As Long

On Error Resume Next
FileNo = FreeFile()

Open FileName For Input Lock Read As #FileNo
Close FileNo

ErrorNo = Err

On Error GoTo 0

Select Case ErrorNo

Case 0
IsWBOpen = False

Case 70
IsWBOpen = True

Case Else
Error ErrorNo

End Select

End Function

ADJUSTABLE PARAMETERS
File Path and Name: Select the file path, including the name of the file, by changing «C:ExcelParameters.xlsx» in the VBA code.
Message if Workbook is Open: Select the message that you want to be displayed if the workbook is open by changing the message «File is Open» in the VBA code.
Message if Workbook is Closed: Select the message that you want to be displayed if the workbook is closed by changing the message «File is Closed» in the VBA code.

ADDITIONAL NOTES
Note 1: This VBA code will check workbooks in all Excel sessions.
Note 2: This method creates a User Defined Function called ‘IsWBOpen’ and then runs the VBA code.

Explanation about how to check if workbook is open

EXPLANATION

EXPLANATION
This tutorial shows how to check if a specific workbook is open in the same Excel session or across all Excel sessions, using VBA.

The first method shows how to check if a workbook, with a specific name, is open in the same Excel session in which the VBA code is run. The second method shows how to check if a specific workbook, including its location and name, is open in all Excel sessions. This is achieved by creating a User Defined Function and then applying this in a macro.

Related Topic Description Related Topic and Description
Check if workbook is open, if closed open workbook How to check if a specific workbook is open and if it’s closed then open the workbook using VBA
Open an Excel workbook How to open a single workbook using Excel, VBA and Shortcut
Open an Excel workbook as Read-Only How to open a single workbook as Read-Only using Excel and VBA

VBA Check if File is Open or not using Excel VBA. In general we automate reports using Excel VBA. When we are dealing with multiple workbooks. It is always better to check whether file is opened or not. After that we can use those files for anything like data analysis, preparing reports etc.

VBA Check if File is Open or not in Excel

Let us see an example to check if file is opened or not using Excel VBA. In the following example we are looping through all opened workbooks and checking specified file is opened or not.

'VBA Check if File is Open
Sub VBAF1_Check_if_File_is_Open()

    'Variable declaration
    Dim sWBName As String
    Dim oWorkbook As Workbook
    Dim bChk As Boolean
    
    'Define file Name
    sWBName = "test.xlsx"
    
    'Loop through all opened workbooks
    For Each oWorkbook In Workbooks
        If oWorkbook.Name = sWBName Then
            'If file is open
            MsgBox "File is opened.", vbInformation, "VBAF1"
            bChk = True
        End If
    Next
    
    'If file is not open
    If bChk = False Then MsgBox "File is not opened.", vbInformation, "VBAF1"
    
End Sub

Output: In the above example we have specified file name as “test.xlsx”. You can change as per your requirement. We have provided comments for set of instructions to make you understand. You can find following screenshot for your reference. It displays when file is opened.
VBA Check if File is Open

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 VBA Text Files VBA Tables

VBA Editor Keyboard Shortcut Keys List VBA Interview Questions & Answers Blog

Option Compare Text ‘Если Вы не понимаете, зачем используется эта инструкция, то оставьте её в покое    

  Private Function WorkbookIsOpen(iName$) As Boolean    
‘***********************************************’    
‘   Дата создания 01/01/2005    
‘   Автор Климов Павел Юрьевич    
‘  

http://www.msoffice.nm.ru    

‘***********************************************’    
   Dim iBook As Workbook    
   For Each iBook In Workbooks    
       If iBook.Name = iName$ Then    
          WorkbookIsOpen = True    
          Exit Function    
       End If    
   Next    
   WorkbookIsOpen = False    
End Function  

  Private Function WorkbookIsOpen(iName$) As Boolean    
‘***********************************************’    
‘   Дата создания 01/01/2005    
‘   Автор Климов Павел Юрьевич    
‘  

http://www.msoffice.nm.ru    

‘***********************************************’    
   Dim iBook As Workbook    
   For Each iBook In Workbooks    
       If StrComp(iBook.Name, iName$, vbTextCompare) = 0 Then    
          WorkbookIsOpen = True    
          Exit Function    
       End If    
   Next    
   WorkbookIsOpen = False    
End Function  
Вариант II.    
Private Function WorkbookIsOpen(iName$) As Boolean    
‘***********************************************’    
‘   Дата создания 01/01/2005    
‘   Автор Климов Павел Юрьевич    
‘  

http://www.msoffice.nm.ru    

‘***********************************************’    
   On Error Resume Next    
   WorkbookIsOpen = IsObject(Workbooks(iName$))    
End Function  

  Private Function WorkbookIsOpen(iName$) As Boolean    
   On Error Resume Next    
   WorkbookIsOpen = (TypeOf Workbooks(iName$) Is Workbook)    
End Function  

  Private Function WorkbookIsOpen(iName$) As Boolean    
   On Error Resume Next    
   WorkbookIsOpen = (TypeName(Workbooks(iName$)) = «Workbook»)    
End Function  

  Private Function WorkbookIsOpen(iName$) As Boolean    
   On Error Resume Next    
   WorkbookIsOpen = (VarType(Workbooks(iName$)) = vbObject)    
End Function  

  Private Function WorkbookIsOpen(iName$) As Boolean    
   On Error Resume Next    
   WorkbookIsOpen = Len(Workbooks(iName$).Name) > 0    
End Function  

  Private Function WorkbookIsOpen(iName$) As Boolean    
   On Error Resume Next    
   WorkbookIsOpen = Workbooks(iName$).Index > 0    
End Function  
Пример вызова любой из вышеопубликованных авторских функций :    
Private Sub Test()    
   MsgBox WorkbookIsOpen(«Имя_Книги.xls»)    
End Sub

In the previous article we have discussed, How to check corruption in Powerpoint file and find a solution to fix it and in this section, we find a solution for MS Excel Users. Every day, hundreds of user deal with corruption issue and try to repair corrupted Excel file. But have you questioned yourself, why corruption occurs? Or How you can check Excel file for corruption issues?

While opening MS 2013 Excel file is throwing error “File cannot open because the file format for the file extension is not valid”  in Windows 7 OS. Don’t know whether the file is corrupted or not, Is there any method to check corruption in Excel File.

excel file

Why Corruption Occurs in MS Excel File?

Various reasons can lead to corruption error and some of the reasons are given below:

  1. Due to sudden power loss might cause the corruption in MS Excel file.
  2. When file is not supported by the currently using MS Excel version.
  3. MS Excel workbooks got attacked by unknown malware or virus.
  4. When a corrupted Excel spreadsheet got downloaded from the attachments.
  5. When hard disk got failed or the Excel file is stored on bad sector of it.
  6. Operating system is facing issues and won’t let you open your Excel file.

How to Check Excel file for Corruption Issues ?

To find the root cause of corruption in MS Excel file and to fix it, User need to perform following tips. It helps to find the actual cause and exact solution according to it.

Trick 1: If corruption occurs in Excel file then data stored in Excel file format either deleted, changed into different character or special character. To check corruption for Excel file, try to open the .xlsx file in other MS Excel application or any other Open Source Excel application. Then check whether check, file is still not showing or previewing the components of the Excel file.

Trick 2: Previous versions issues: Sometimes user try to open Excel file created in Older versions of MS Excel environment but error occur. Even sometimes file downloaded as an attachment from Web or another source can lead to changes. To deal with these scenarios and to check excel file for corruption issue. You can check the Check security permissions of MS Excel File file. Just follow the easy steps:

1) Go to Properties.

2) Enable the modes in security feature.

3) After allowing the permission, you still face the issue then, then there is chance of corruption in Excel File

Trick 3: Some time file is not corrupted, but due to some hard drive failure issue, error occur and file not opening properly. To deal with this situation try to move all desired file it to another system or other drive. Then try to open it the Excel file. If it opens, file is not corrupted.

Trick 4: When Excel default set as open in safe mode, it shows only the blank Excel document. To rectify this, do the manual procedure of opening the MS Excel in Safe Mode. Follow the simple steps.

  1. Press (Windows + R) key together, command prompt Window will open.
  2. Type “excel.exe /s” in command prompt, click to “OK”.

3. MS Excel is now opened in the safe mode, click to File.

4. Select Open, and choose the corrupted MS Excel file.

Trick 5: To check corruption in Excel File, you can also use Web Services available on Web to check and fix corruption issue of Excel File  If your file is corrupted then you can fix excel file for corruption via online checker.

online-repair

In this, you can easily detect or check Excel file for corruption in 2013. If there is high-level corruption, it must display some error. Read the popular Excel file error in the next section.

Error Message Displays When Excel File is Corrupted

You can memories these error messages as, it occurs when the Excel file is corrupted. In future, it help you to differentiate between the errors occurs due to corruption & which occurs due to other reasons.

Now you know how to check Excel file for corruption and errors thrown by corrupted Excel file. It’s time to rectify the corruption issue & errors, there are some methods and tricks for it.

How to Resolve Microsoft Excel File Corruption & Errors?

You can handle corruption issue and these error messages by the given manual methods. Here, some manual methods are enlisted:

Method 1: MS Excel Open and Repair Feature.

Method 2: Changes in the Excel File Extension.

Method 3: Open Excel Workbook in Safe Mode.

When the manual methods fails, what will you do? Do not take stress, you are still able to detect or check Excel file for corruption and rectify them by this automated solution. Continue reading.

Instant Solution

This solution will fix corruption and corrupted Excel files in no time. Excel File Recovery Tool is the ultimate utility to resolve corruption issues. By using the advanced algorithm, this utility is specially designed for facing errors occur due to corruption. It will automatically check Excel file for corruption issues and repair.

Moreover, it has recovery modes & Inbuilt preview feature for users compatibility. It supports MS Excel 2007, 2010, 2013, 2016 & 2019 versions. It provides a user-friendly interface for naive users. Try the demo version of this utility, available on its website.

Conclusion

Hopefully, this article answered most of the user’s queries. I tried to fetch every detail from the possible resources to provide you the exact solution. This article conveys possible solution to check Excel file for corruption.  

See more:

Hi, I need help how I can check that Excel file is open which one I am going to browse to upload, i want particular Excel file if opened then save automatically and close that excel file because I am having an error when I am going to upload excel data in Data table.
following error is coming

Quote:

The Microsoft Access database engine cannot open or write to the file ». It is already opened exclusively by another user, or you need permission to view and write its data

What I have tried:

I was trying to close excel file which one i am going to upload data, but i want check if open then close, this code does not work

Microsoft.Office.Interop.Excel.Application Excel = new Microsoft.Office.Interop.Excel.Application();
                    Microsoft.Office.Interop.Excel.Workbook workbook;
                    Microsoft.Office.Interop.Excel.Worksheet xlWorkSheet;
                    object misValue = System.Reflection.Missing.Value;
                    workbook = Excel.Workbooks.Add(txtBrowse.Text);
                    workbook.Close(false, misValue, misValue);

Comments


Solution 1

Check whether it is open like

try
{
   Stream s = File.Open(FileName, FileMode.Open, FileAccess.Read, FileShare.None);

   s.Close();

   return true;
}
catch (Exception)
{
   return false;
}

Close Excel like as:-

using Excel = Microsoft.Office.Interop.Excel;

# declare the application object
Excel.Application xl = new Excel.Application();

# open a file
Excel.Workbook wb = xl.Workbooks.Open("some_file.xlsx");

# do stuff ....

# close the file
wb.Close();

# close the application and release resources
xl.Quit();

Comments

Solution 3

protected virtual bool IsFileLocked(FileInfo file)
{
FileStream stream = null;

try
{
stream = file.Open(FileMode.Open, FileAccess.Read, FileShare.None);
}
catch (IOException ex)
{
//the file is unavailable because it is:
//still being written to
//or being processed by another thread
//or does not exist (has already been processed)
return true;
}
finally
{
if (stream != null)
stream.Close();
}

//file is not locked
return false;
}

Comments

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

 

Print

Answers RSS

Top Experts
Last 24hrs This month

CodeProject,
20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8
+1 (416) 849-8900

Get our FREE VBA eBook of the 30 most useful Excel VBA macros.

Automate Excel so that you can save time and stop doing the jobs a trained monkey could do.

Claim your free eBook


VBA Code Snippets

If you work in a team, there are times when more than one person tries to use a file.  Maybe your line manager is checking a piece of information in a workbook, whilst at the same time you are trying to rename the file.  When you’re running files manually, it normally provides a reasonable warning message, but if you’re trying to do this with a macro you will probably receive this type of error:

VBA file open Run-time error '75' File Path access error

If other users will be using your macro, chances are that they will have no idea what this error means.  The code below will check to see if the file is already open by you, or another user.  If it is open, or un-editable for any reason, you will be able to stop the macro from running or display a meaningful error message to the user.

The function has 3 possible results:

  • True = The file is already open
  • False = The file is currently closed
  • [Error Number] = Something else has gone wrong, so the error number is returned.
Function IsFileOpen(fileName As String)

Dim fileNum As Integer
Dim errNum As Integer

'Allow all errors to happen
On Error Resume Next
fileNum = FreeFile()

'Try to open and close the file for input.
'Errors mean the file is already open
Open fileName For Input Lock Read As #fileNum
Close fileNum

'Get the error number
errNum = Err

'Do not allow errors to happen
On Error GoTo 0

'Check the Error Number
Select Case errNum

    'errNum = 0 means no errors, therefore file closed
    Case 0
    IsFileOpen = False
 
    'errNum = 70 means the file is already open
    Case 70
    IsFileOpen = True

    'Something else went wrong
    Case Else
    IsFileOpen = errNum

End Select

End Function

Remember: Functions must be placed into a Module to work correctly.

The following procedure shows how to call the above function.

Sub CheckIfFileOpen()

Dim fileName As String
fileName = "C:UsersmarksDocumentsAlready Open.xlsx"

'Call function to check if the file is open
If IsFileOpen(fileName) = False Then

    'Insert actions to be performed on the closed file

Else

    'The file is open or another error occurred
    MsgBox fileName & " is already open."

End If

End Sub

Headshot Round

About the author

Hey, I’m Mark, and I run Excel Off The Grid.

My parents tell me that at the age of 7 I declared I was going to become a qualified accountant. I was either psychic or had no imagination, as that is exactly what happened. However, it wasn’t until I was 35 that my journey really began.

In 2015, I started a new job, for which I was regularly working after 10pm. As a result, I rarely saw my children during the week. So, I started searching for the secrets to automating Excel. I discovered that by building a small number of simple tools, I could combine them together in different ways to automate nearly all my regular tasks. This meant I could work less hours (and I got pay raises!). Today, I teach these techniques to other professionals in our training program so they too can spend less time at work (and more time with their children and doing the things they love).


Do you need help adapting this post to your needs?

I’m guessing the examples in this post don’t exactly match your situation. We all use Excel differently, so it’s impossible to write a post that will meet everybody’s needs. By taking the time to understand the techniques and principles in this post (and elsewhere on this site), you should be able to adapt it to your needs.

But, if you’re still struggling you should:

  1. Read other blogs, or watch YouTube videos on the same topic. You will benefit much more by discovering your own solutions.
  2. Ask the ‘Excel Ninja’ in your office. It’s amazing what things other people know.
  3. Ask a question in a forum like Mr Excel, or the Microsoft Answers Community. Remember, the people on these forums are generally giving their time for free. So take care to craft your question, make sure it’s clear and concise.  List all the things you’ve tried, and provide screenshots, code segments and example workbooks.
  4. Use Excel Rescue, who are my consultancy partner. They help by providing solutions to smaller Excel problems.

What next?
Don’t go yet, there is plenty more to learn on Excel Off The Grid.  Check out the latest posts:

April 2023 Community Newsletter

Welcome to our April 2023 Community Newsletter, where we’ll be highlighting the latest news, releases, upcoming events, and the great work of our members inside the Biz Apps communities. You can subscribe to the News & Announcements and stay up to date with the latest news from our ever-growing membership network who quickly discover that «Community is bigger on the inside». 
 

 
 
LATEST NEWS
Microsoft Business Applications Launch Event — On Demand
Sign up below for an in-depth look into the latest updates from across Microsoft #PowerPlatform and #Dynamics365. Find out about new features, capabilities, and best practices for connecting data to deliver exceptional customer experiences, collaborating using AI-powered analytics, and driving productivity with automation. Guest speakers include Charles Lamanna, Emily He, Georg Glantschnig, Julie Strauss, Jeff Comstock, Lori Lamkin, Mike Morton, Ray Smith, and Walter Sun.
 

Watch Now: Business Applications Launch Event

 
 
Power Platform Connections — Episode Nine
Episode Nine of #PowerPlatform Connections premieres today at 12pm PST, as David Warner II and Hugo Bernier chat to Principal Program Manager Vesa Juvonen, alongside the great work of Troy Taylor, Geetha Sivasailam, Michael Megel, Nathalie Leenders, Ritesh Ranjan Choubey, Clay Wesener, Tristan DEHOVE, Dian Taylor, and Cat Schneider.
Click the link below to subscribe and get notified, with David and Hugo LIVE in the YouTube chat from 12pm PST. And remember to use the hashtag #PowerPlatformConnects on social to have your work featured on the show!
 

 
 
App in a Day — Free Workshop
Looking for a way to build a solution to quickly meet your business needs? Register below for a FREE «App in a Day» workshop to find out how to create custom business applications without writing code!
Microsoft Power Platform In a Day workshops

 
UPCOMING EVENTS
Directions Asia
Find out more about Directions 4 Partners Asia 2023, which will be taking place in Bangkok on 27-28th April 2023, featuring key speakers Mike Morton, Jannik Bausager and Dmitry Chadayev.
This event is for SMB focused Dynamics partners and their employees to receive product knowledge about Business Central, Power Platform and #DynamicsSales, and to be inspired and motivated by best practices, expert knowledge and innovative ideas.
If you want to meet industry experts, gain an advantage in the SMB-market, and acquire new knowledge about #MicrosoftDynamics Business Central, click the link below to buy your ticket today!
 
Click here to Register  

 
 
Iberian Tech Summit
Come take a look at the Iberian Technology Summit which will be held at the Real Marina Hotel & Spa in Olhão, Portugal, between 28-30th April 2023.
The Iberian Technology Summit is the first of its kind with a clear goal to achieve — cross the borders of peninsula and help to empower the community of professionals, workers and businesses to grow stronger together.
Congrats to Kaila Bloomfield, Adam B., Ana Inés Urrutia de Souza and the team for putting together this great event. Click below to find out more details.
Click here to Register

 
 
Power Platform Conference 2023
We are so excited to see you for the Microsoft Power Platform Conference in Las Vegas October 3-5th, 2023! But first, let’s take a look back at some fun moments and the best community in tech from MPPC 2022 in Orlando Florida.
 

Featuring guest speakers such as Heather Cook, Julie Strauss, Nirav Shah, Ryan Cunningham, Sangya Singh, Stephen Siciliano, Hugo Bernier and many more, click the link below to register for the 2023 #MPPC23 today! 
www.powerplatformconf.com
 
COMMUNITY HIGHLIGHTS
Check out our top Super and Community Users reaching new levels! These hardworking members are posting, answering questions, kudos, and providing top solutions in their communities.
Power Apps: 
Super Users:  @BCBuizer , @WarrenBelz, 
Community Users: @mmollet, @Amik, @RJM07 
 
Power Automate: 
Super Users: @Expiscornovus , @grantjenkins, @abm 
Community Users: @Nived_Nambiar  
 
Power Virtual Agents: 
Super Users: @Expiscornovus, @Pstork1, 
Community Users: @nikviz, @DaniBaeyens 
 
Power Pages:
Super Users: @ragavanrajan 
Community Users: @OOlashyn, @gospa, @Fubar 

LATEST PRODUCT BLOG ARTICLES 
Power Apps Community Blog 
Power Automate Community Blog 
Power Virtual Agents Community Blog 
Power Pages Community Blog 

Check out ‘Using the Community’ for more helpful tips and information: 
Power Apps, Power Automate, Power Virtual Agents, Power Pages 

Понравилась статья? Поделить с друзьями:
  • Excel charts что это
  • Excel cell to string vba
  • Excel cell text not value
  • Excel cell text not formula
  • Excel cell reference in formula