Vba проверить открыт ли файл word

  • Remove From My Forums
  • Question

  • I wish to open a MS Word document by clicking on a button in an excel worksheet, but I need to check first to see if the document is already open.  The following code works correctly if the document is NOT open, but I need a way to deal with the «already
    open» situation. Currently the «Already Open» dialogue box appears, and when I click Cancel, the Word background is displayed with no document Showing.  Ideally the code would simply bring the requested already open document to the front, but an alternative
    would be to generate a message box telling me it was already open.

    Sub HelpAndInfo()

    ‘Open Help and Information Document
    Dim Wd As Object
    Dim HelpDoc As Object

        On Error GoTo Unset

        
        Set Wd = CreateObject(«Word.Application»)

        ‘If the doc is already open the next line pulls up the «Already Open» dialogue box .

        Set HelpDoc = Wd.Documents.Open(«C:UsersNAMEDocumentsComputerVBASpdSheetNotes.doc»)
        Wd.Visible = True

        
        On Error GoTo 0

    Unset:
        Set Wd = Nothing
        Set HelpDoc = Nothing

    End Sub

    Any help gratefully received.

Answers

  • Try this version:

    Sub HelpAndInfo()
        'Open Help and Information Document
        Const strpath = "C:UsersNAMEDocumentsComputerVBASpdSheetNotes.doc"
        Dim Wd As Object
        Dim HelpDoc As Object
        Dim f As Boolean
        On Error Resume Next
        Set HelpDoc = GetObject(strpath)
        If HelpDoc Is Nothing Then
            Set Wd = GetObject(, "Word.Application")
            If Wd Is Nothing Then
                Set Wd = CreateObject("Word.Application")
                If Wd Is Nothing Then
                    MsgBox "Failed to start Word!", vbCritical
                    Exit Sub
                End If
                f = True
            End If
            Set HelpDoc = Wd.Documents.Open(strpath)
            If HelpDoc Is Nothing Then
                MsgBox "Failed to open help document!", vbCritical
                If f Then
                    Wd.Quit
                End If
                Exit Sub
            End If
            Wd.Visible = True
        Else
            With HelpDoc.Parent
                .Visible = True
                .Activate
            End With
        End If
    End Sub
    


    Regards, Hans Vogelaar

    • Marked as answer by

      Friday, December 28, 2012 6:30 PM

Spirtuoz

0 / 0 / 0

Регистрация: 31.01.2021

Сообщений: 1

1

Проверка, открыт ли Ворд

31.01.2021, 22:25. Показов 3837. Ответов 4

Метки нет (Все метки)


Студворк — интернет-сервис помощи студентам

Добрый день! Столкнулся с таким вопросом.

Данный код открывает целевой документ Word

Visual Basic
1
2
3
4
Set wd = New Word.Application
Set wdDoc = wd.Documents.Open _
(ThisWorkbook.Path & "" & "Акт.docm")
wd.Visible = True

Однако, если данный документ уже открыт, макрос с данным кодом зависает. Как сделать, чтобы он проверял, открыт ли данный файл («Акт.docm») и:
— если открыт, то переходил к следующему действию
— если закрыт то использовался код выше и переходил к следующему действию.

Надеюсь на вашу помощь.



0



4038 / 1423 / 394

Регистрация: 07.08.2013

Сообщений: 3,541

01.02.2021, 03:34

2

можно проверить наличие файла с именем
Chr(129) & «$т.docm»
в папке где расположен ваш файл Акт.docm
если есть то файл открыт



0



810 / 465 / 180

Регистрация: 09.03.2009

Сообщений: 1,577

01.02.2021, 11:29

3

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



0



NewMaNew

5 / 5 / 0

Регистрация: 02.09.2020

Сообщений: 32

01.02.2021, 12:25

4

прошу прощения, не то ответил

Добавлено через 10 минут
решение:

Visual Basic
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
Function FileInWordOpen(DokName As String) As Boolean
Dim wd
wd = CreateObject("Word.Application")
Dim wDoc
wDoc = CreateObject("Word.Document")
 
Dim i As Long, s As String
On Error Resume Next
Set wd = GetObject(, "Word.Application")
On Error GoTo NO_WORD_FOUND
If wd Is Nothing Then
    FileInWordOpen = False
End If
For i = 1 To wd.Documents.Count
  s = wd.Documents(i)
  If InStr(DokName, s) <> 0 Then
     FileInWordOpen = True
     Exit Function
  End If
Next
 
NO_WORD_FOUND:
 
 FileInWordOpen = False
 
 End Function
Sub testdocopened()
Debug.Print FileInWordOpen("test.docx")
End Sub



0



Alex77755

11482 / 3773 / 677

Регистрация: 13.02.2009

Сообщений: 11,145

01.02.2021, 14:00

5

Попадалась функция проверки открыт ли файл:

Visual Basic
1
2
3
4
5
6
Function IsBookOpen(wbFullName As String) As Boolean
    On Error Resume Next
    Open wbFullName For Random Access Read Write Lock Read Write As 1
    close 1
    IsBookOpen = Err
End Function



0



Sub макрос()

        Dim doc As Document

            ‘ Включение перехватчика run-ошибок, чтобы макрос продолжил работу при возникновении
        ‘ run-ошибки.
    On Error Resume Next
        ‘ Присваиваем файлу имя «doc». Если файл не открыт, то в переменной «doc» будет Nothing.
        Set doc = Documents(«C:UsersUserDesktopДокумент Microsoft Word.docx»)
    ‘ Отключение перехватчика ошибок, чтобы видеть непредвиденные ошибки.
    On Error GoTo 0

        ‘ Проверка, открыт файл или нет.
    If doc Is Nothing Then
        MsgBox «Файл не открыт.», vbInformation
    Else
        MsgBox «Файл открыт.», vbInformation
    End If

End Sub

[свернуть]

Before opening a Word file, I want to check if this file is already open. (More word files are open at the same time)
The main sub calls this function to tell me if it’s open or not.

Function FileInWdOpen(DokName As String) As Boolean                 

    Dim wd As Word.Application
    Dim wDoc As Word.Document

    On Error Resume Next                                            
    Set wd = GetObject(, "Word.Application")
    On Error GoTo NO_WORD_FOUND                                     

    If wd Is Nothing Then                                           
        FileInWdOpen = False
    End If

    For Each wDoc In wd.Documents        'should check for every open word file but doesn't do that                         
        If wDoc.Name = DokName Then      'checks if this file is named like the one I want to check if its open or not                           
            FileInWdOpen = True
            Exit Function                                           
        End If
    Next                                                            

    FileInWdOpen = False                                            

    Exit Function

NO_WORD_FOUND:       

    FileInWdOpen = False                                            

End Function

This code works out well when only one word file is open. If two or more files are open, the script don’t work.

The problem is that the for loop only checks the first file that is open.

I don’t understand why it don’t check all open files.
I thought it’s possible to access all Documents with:

Dim WordApp As Word.Application                 'sets an var for the Word Application
Set WordApp = GetObject(, "Word.Application")   'give the var an obj, in this case the Word Application

Dim WordDoc As Word.Document                    'sets an var for the singel Word Documents
For Each WordDoc In WordApp.Documents           'for each Document in Dokuments
    'code
Next

So why only the first document gets attention?

Группа: Пользователи

Ранг: Прохожий

Сообщений: 7


Репутация:

0

±

Замечаний:
0% ±


Добрый день! Столкнулся с таким вопросом.

Данный код открывает целевой документ Word
[vba]

Код

Set wd = New Word.Application
Set wdDoc = wd.Documents.Open _
(ThisWorkbook.Path & «» & «Акт.docm»)
wd.Visible = True

[/vba]

Однако, если данный документ уже открыт, макрос зависает. Как сделать, чтобы он проверял, открыт ли данный файл («Акт.docm») и
— если открыт, то переходил к следующему действию
— если закрыт то использовался код выше и переходил к следующему действию.

Надеюсь на вашу помощь.

Формулировка задачи:

Добрый день!
Проблема следующая: на диске лежит файл word, его могут открывать кто угодно. Если пользователь открывает файл, и потом не закрывает его, то при следующем открытии, word предлагает открыть файл в режиме readonly, что логично Можно ли как-нибудь перед открытием узнать открыт ли данный файл?

Код к задаче: «Как узнать открыт ли Word файл?»

textual

Option Explicit
Dim i As String
Dim Workbook As Object
 
Private Sub CommandButton1_Click()
i= 'Добро пожаловать.'
For Each Workbook In Application.Workbooks
If Workbook.Name = 'Книга1.xls' Then i = 'Файл уже открыт для изменений!'
Next
MsgBox i
End Sub

Полезно ли:

13   голосов , оценка 4.154 из 5

Понравилась статья? Поделить с друзьями:
  • Vba последняя запись в excel
  • Vba поиск слова во всем excel
  • Vba поиск символов в ячейке excel
  • Vba поиск подстроки в word
  • Vba подсчет заполненных ячеек в excel