Vba только для чтения word на

Every time I try to open a word document in VBA excel I get a pop up window in the background that asks me how to open it because it is tagged as read-only. I have looked at the properties of the file and it isn’t read-only however it is in revision control (tortoise-SVN).

Sub ReadSpec()
'References
'  Microsoft Word 14.0 Object library
'
Dim Paragraphe As Object

Dim WordApp As Word.Application
Set WordApp = CreateObject("Word.Application")

Dim WordDoc As Word.Document
Set WordDoc = WordApp.Documents.Open("Spec.docx")
WordApp.Visible = True

WordDoc.Close
WordApp.Quit


End Sub

David Zemens's user avatar

David Zemens

52.8k11 gold badges79 silver badges129 bronze badges

asked Jun 10, 2013 at 13:55

engineer Mike's user avatar

2

The file may be in use by another application which is why you’re being told it is read-only. This isn’t a problem unless you want to write to the file. If you’re only trying to read from it my suggestion is to add

Application.DisplayAlerts = False

to see if it gets rid of the prompt for you. Also note that it is generally good practice to do something more along the lines of

Sub YourMethod
    Dim PrevDispAlerts as Boolean

    PrevDispAlerts = Application.DisplayAlerts
    Application.DisplayAlerts = False

    'code that does something goes here

    Application.DisplayAlerts = PrevDispAlerts
End Sub

answered Jun 10, 2013 at 14:03

Ripster's user avatar

RipsterRipster

3,5252 gold badges19 silver badges28 bronze badges

0

I’m not familiar with SVN but you might try either:

.Open("Spec.docx", ReadOnly=False) 

or

.Open("Spec.docx", ConfirmConversions=False, ReadOnly=False)

These suppress two common dialogs and force the default behavior. If you needed to override you would have to either make that explicit in the above code (i.e., ReadOnly=True to force read only) or just allow the dialog to display, using your original code.

answered Jun 10, 2013 at 21:54

David Zemens's user avatar

David ZemensDavid Zemens

52.8k11 gold badges79 silver badges129 bronze badges

I suppose it depends on the version of Excel. Solutions often work for one version but not another.

http://smallbusiness.chron.com/open-word-document-excel-using-vba-40430.html

I found this code worked.

'Open an existing Word Document from Excel
Dim objWord As Object
Set objWord = CreateObject("Word.Application")
objWord.Visible = True
'Change the directory path and file name to the location
'of the document you want to open from Excel
objWord.Documents.Open "C:Documentsmyfile.doc"

answered Jul 20, 2013 at 13:06

user2602261's user avatar

hmmm not familiar with SVN but you might try

 .Open("Spec.docx", ReadOnly=False) or Open("Spec.docx", ConfirmConversions=False, ReadOnly=False)

answered Jun 10, 2013 at 21:43

engineer Mike's user avatar

engineer Mikeengineer Mike

772 gold badges2 silver badges7 bronze badges

1

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

подскажите как при помощи ВБА
уточнить файл Ворд открыт только для чтения?
если да — тогда сделать его в обычном режиме то есть не только для чтения
потом произвести нужное
и
снова сделать для чения
Вроде по последнему строка кода есть:

Visual Basic
1
SetAttr ActiveDocument.Path & "" & ActiveDocument.Name, vbReadOnly

Добавлено через 2 часа 36 минут
сейчас не могу проверить, может так:

Visual Basic
1
2
3
4
5
6
If ActiveDocument.ReadOnly = False Then
MsgBox$  "Файл открыт только для чтения"
SetAttr ActiveDocument.FullName, vbReadOnly = False 
нужные действия
SetAttr ActiveDocument.FullName, vbReadOnly
End If
title keywords f1_keywords ms.prod api_name ms.assetid ms.date ms.localizationpriority

Document.ReadOnly property (Word)

vbawd10.chm158007340

vbawd10.chm158007340

word

Word.Document.ReadOnly

57421a93-808f-f216-5110-0c3b80cf6e04

06/08/2017

medium

Document.ReadOnly property (Word)

True if changes to the document cannot be saved to the original document. Read-only Boolean.

Syntax

expression.ReadOnly

expression Required. A variable that represents a Document object.

Example

This example saves the active document if it isn’t read-only.

If ActiveDocument.ReadOnly = False Then ActiveDocument.Save

See also

Document Object

[!includeSupport and feedback]

Sub P2()
Dim Путь As String
Dim Атрибуты As Integer
'Если документ открыт только для чтения, то:
If ActiveDocument.ReadOnly = True Then
    'Записываем путь к файлу (т.к. его придётся заново открывать).
    Путь = ActiveDocument.FullName
    'Записываем в переменную Атрибуты, какие атрибуты есть у файла,
    'чтобы затем вернуть их на место (они выражаются в числах).
    'Эти атрибуты находятся: щ. правой кн. мыши по файлу - Свойства.
    Атрибуты = GetAttr(PathName:=Путь)
    'Стираем все атрибуты файла, кроме Normal. Вдруг среди них
    'есть атрибут Только чтение.
    SetAttr PathName:=Путь, Attributes:=vbNormal
    'Закрываем документ, чтобы можно было открыть для редактирования.
    ActiveDocument.Close SaveChanges:=wdDoNotSaveChanges
    'Открываем документ для редактирования.
    Documents.Open FileName:=Путь
    'Здесь выполняются действия с документом.
    MsgBox "Документ открыт для редактирования"
    'Закрываем документ, чтобы снова открыть в режиме Только чтение.
    ActiveDocument.Close
    'Восстанавливаем атрибуты файла.
    SetAttr PathName:=Путь, Attributes:=Атрибуты
    'Открываем документ в режиме Только чтение.
    Documents.Open FileName:=Путь, ReadOnly:=True
Else
    'Если документ был с самого начала открыт для редактирования.
    MsgBox "Документ не был открыт только для чтения"
End If
End Sub

Установка/снятие атрибута «Только чтение»

'требуется ссылка на scrrun.dll (Microsoft Scripting Runtime)

'Установка атрибута "Только чтение"
Sub SetReadOnly(Path As String)
  Dim fso As New FileSystemObject, f As File
  Set f = fso.GetFile(Path)
  f.Attributes = f.Attributes Or ReadOnly
End Sub

'Снятие атрибута "Только чтение"
Sub RemoveReadOnly(Path As String)
  'Shell "ATTRIB -R " & Path, vbHide
  Dim fso As New FileSystemObject, f As File
  Set f = fso.GetFile(Path)
  f.Attributes = f.Attributes Xor ReadOnly
End Sub

Запись опубликована в рубрике программирование с метками файлы, VBA, WSH. Добавьте в закладки постоянную ссылку.

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