Vba ошибка 5174

I need to check whether a file is present in the directory.

If file NOT present i should create a new one.

But at run time the Excel gives an error;

«Run-time error 5174: Application defined or object defined error».

Is there any exception handling technique in VBA to catch these run time error?

How can i overcome this issue so that i can create a file if non existant?

Dim savename, FileExt, FileName As String
Dim i, finalrow As Integer
Dim wdvar As Word.Application
Dim wrdDoc As Word.Document

Set wdvar = CreateObject("Word.Application")
wdvar.Visible = True         

FileName = Environ("UserProfile") & "DesktopReport.docx"
Set wrdDoc = wdvar.Documents.Open(FileName)

With wdvar
    .Visible = True
    .Activate


   .Documents.Add

R3uK's user avatar

R3uK

14.4k7 gold badges43 silver badges77 bronze badges

asked Oct 5, 2016 at 9:47

Prabhu's user avatar

add a reference to Microsoft Scripting Runtime and use the Scripting.FilesystemObject.
It has a nice handy «FileExists()» function that you can use to test if a file exists.

   Dim fso as new Scripting.FileSystemobject

   If (fso.FileExists(strPath)) Then
      debug.print "File Exists"
   Else
      debug.print "File Not Found"
   End If

answered Oct 5, 2016 at 11:06

Joe Bourne's user avatar

Joe BourneJoe Bourne

1,13410 silver badges18 bronze badges

The error handling can be done like this:

sub Main
Dim savename, FileExt, FileName As String
Dim i, finalrow As Integer
Dim wdvar As Word.Application
Dim wrdDoc As Word.Document

On Error GoTo Main_Error

Set wdvar = CreateObject("Word.Application")
wdvar.Visible = True         

FileName = Environ("UserProfile") & "DesktopReport.docx"
Set wrdDoc = wdvar.Documents.Open(FileName)

With wdvar
    .Visible = True
    .Activate


   .Documents.Add
'...
on error goto 0
exit sub
Main_error
   if err.number = 5174 then
   'you may write something here
else
   'normally a msgbox for the error 
end if
end sub

Additionally 1: if you want to create the file, you may do it from the error handler or you can simply check whether the file is existing. Depends what you want: -> http://www.rondebruin.nl/win/s9/win003.htm

Additionally 2:
do not use integers, but use long, and declare each variable on a separate line, otherwise you declare them as vars.

answered Oct 5, 2016 at 9:57

Vityata's user avatar

VityataVityata

42.4k8 gold badges54 silver badges99 bronze badges

0

Personnaly, I use this function :

Public Function File_Exist(sFilePath As String) As Boolean
    Dim sProv As String
    On Error GoTo ErrorHandler
        sProv = Dir(sFilePath, vbDirectory)

        File_Exist = (sProv <> "")
    On Error GoTo 0
    Exit Function

ErrorHandler:
    MsgBox prompt:="Error on test file= " & sFilePath & vbCrLf & _
           Err.Number & vbCrLf & Err.Description
End Function

Where do you need to use it :

If File_Exist(Filename) Then
    Set wrdDoc = wdvar.Documents.Open(Filename)
Else
    With wdvar
        .Visible = True
        .Activate

       .Documents.Add
    End With
End If

answered Oct 5, 2016 at 10:07

R3uK's user avatar

R3uKR3uK

14.4k7 gold badges43 silver badges77 bronze badges

3

In Microsoft Word 2010 VBA

I am getting a runtime error 5174, when trying to open a document which file name includes a pound sign «#», with a relative file path.

Sub openPoundedFilename()
    Dim doc As Object
    ' Both files "C:Tempfoo_bar.docx" and "C:Tempfoo#bar.docx" exist

    ' With absolute file paths
    Set doc = Documents.Open(fileName:="C:Tempfoo_bar.docx") ' Works
    doc.Close
    Set doc = Documents.Open(fileName:="C:Tempfoo#bar.docx") ' Works
    doc.Close

    ' With relative file paths
    ChDir "C:Temp"
    Set doc = Documents.Open(fileName:="foo_bar.docx") ' Works
    doc.Close
    Set doc = Documents.Open(fileName:="foo#bar.docx") ' Does not work !!!!
    'Gives runtime error 5174 file not found (C:Tempfoo)
    doc.Close
End Sub

I did not find any explanation for why the last Documents.Open fails.

It probably has to do with some mismatch regarding the «#» sign used for URL.

(see https://support.microsoft.com/en-us/kb/202261)

Thanks in advance for answers


Edit 17/10/2016 13:37:17

The macro recording generates the following:

Sub Macro1()
'
' Macro1 Macro
'
'
    ChangeFileOpenDirectory "C:Temp"
    Documents.Open fileName:="foo#bar.docx", ConfirmConversions:=False, _
        ReadOnly:=False, AddToRecentFiles:=False, PasswordDocument:="", _
        PasswordTemplate:="", Revert:=False, WritePasswordDocument:="", _
        WritePasswordTemplate:="", Format:=wdOpenFormatAuto, XMLTransform:=""
End Sub

This macro doesn’t work (gives the same error 5174).

Old

09-15-2013, 05:12 AM

tinfanide
tinfanide is offline

Run-time Error 5174: Open Word Documents from Excel Windows 7 64bit Run-time Error 5174: Open Word Documents from Excel Office 2010 32bit

Expert

Run-time Error 5174: Open Word Documents from Excel

 

Join Date: Aug 2011

Posts: 312

tinfanide is on a distinguished road

Default

Run-time Error 5174: Open Word Documents from Excel


Early binding; opening a Word Document from Excel VBA.
First time, no error.
Starting from then, it returns the error stated in the codes below:

How could I fix it?

Code:

Public Sub SendToWord()

Dim myWord As Word.Application
Set myWord = New Word.Application
With myWord
    .Visible = True
    ''' Run-time Error 5174
    ''' Application-defined Error or Object-defined Error
    myWord.Documents.Open Filename:="1.doc"
End With

Reply With Quote

Old

10-01-2013, 01:11 AM

Default


Quote:

Originally Posted by tinfanide
View Post

Early binding; opening a Word Document from Excel VBA.
First time, no error.
Starting from then, it returns the error

Could be a timing issue. You might need to set up a loop to test whether the Word app has loaded before continuing.

__________________
Cheers,
Paul Edstein
[Fmr MS MVP — Word]

Reply With Quote

Old

10-01-2013, 01:23 AM

tinfanide
tinfanide is offline

Run-time Error 5174: Open Word Documents from Excel Windows 7 64bit Run-time Error 5174: Open Word Documents from Excel Office 2010 32bit

Expert

Run-time Error 5174: Open Word Documents from Excel

 

Join Date: Aug 2011

Posts: 312

tinfanide is on a distinguished road

Default


Yes, it might be.

Reply With Quote

Old

10-01-2013, 07:35 AM

BobBridges's Avatar

BobBridges
BobBridges is offline

Run-time Error 5174: Open Word Documents from Excel Windows 7 64bit Run-time Error 5174: Open Word Documents from Excel Office 2010 32bit

Expert

 

Join Date: May 2013

Location: USA

Posts: 695

BobBridges has a spectacular aura aboutBobBridges has a spectacular aura about

Default


When I google 5174 for VBA/Word, it seems always to be the file-not-found error. Are you sure you’re getting the error at the .Visible=True statement rather than the .Open statement? (Of course that doesn’t explain why the file may have disappeared, but still, first things first.)

Reply With Quote

#vba #excel #ms-word

#vba #excel #ms-word

Вопрос:

Мне нужно проверить, присутствует ли файл в каталоге.

Если файл ОТСУТСТВУЕТ, я должен создать новый.

Но во время выполнения Excel выдает ошибку;

«Ошибка 5174 во время выполнения: ошибка, определенная приложением или объектом».

Существует ли какой-либо метод обработки исключений в VBA для обнаружения этих ошибок во время выполнения?

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

 Dim savename, FileExt, FileName As String
Dim i, finalrow As Integer
Dim wdvar As Word.Application
Dim wrdDoc As Word.Document

Set wdvar = CreateObject("Word.Application")
wdvar.Visible = True         

FileName = Environ("UserProfile") amp; "DesktopReport.docx"
Set wrdDoc = wdvar.Documents.Open(FileName)

With wdvar
    .Visible = True
    .Activate


   .Documents.Add
  

Ответ №1:

добавьте ссылку на Microsoft Scripting Runtime и используйте Scripting.FileSystemObject. Он имеет приятную удобную функцию «FileExists ()», которую вы можете использовать для проверки, существует ли файл.

    Dim fso as new Scripting.FileSystemobject

   If (fso.FileExists(strPath)) Then
      debug.print "File Exists"
   Else
      debug.print "File Not Found"
   End If
  

Ответ №2:

Обработка ошибок может быть выполнена следующим образом:

 sub Main
Dim savename, FileExt, FileName As String
Dim i, finalrow As Integer
Dim wdvar As Word.Application
Dim wrdDoc As Word.Document

On Error GoTo Main_Error

Set wdvar = CreateObject("Word.Application")
wdvar.Visible = True         

FileName = Environ("UserProfile") amp; "DesktopReport.docx"
Set wrdDoc = wdvar.Documents.Open(FileName)

With wdvar
    .Visible = True
    .Activate


   .Documents.Add
'...
on error goto 0
exit sub
Main_error
   if err.number = 5174 then
   'you may write something here
else
   'normally a msgbox for the error 
end if
end sub
  

Дополнительно 1. если вы хотите создать файл, вы можете сделать это из обработчика ошибок или просто проверить, существует ли файл. Зависит от того, что вы хотите: -> http://www.rondebruin.nl/win/s9/win003.htm

Дополнительно 2. не используйте целые числа, а используйте long и объявляйте каждую переменную в отдельной строке, в противном случае вы объявляете их как переменные.

Ответ №3:

Лично я использую эту функцию :

 Public Function File_Exist(sFilePath As String) As Boolean
    Dim sProv As String
    On Error GoTo ErrorHandler
        sProv = Dir(sFilePath, vbDirectory)

        File_Exist = (sProv <> "")
    On Error GoTo 0
    Exit Function

ErrorHandler:
    MsgBox prompt:="Error on test file= " amp; sFilePath amp; vbCrLf amp; _
           Err.Number amp; vbCrLf amp; Err.Description
End Function
  

Где вам нужно его использовать :

 If File_Exist(Filename) Then
    Set wrdDoc = wdvar.Documents.Open(Filename)
Else
    With wdvar
        .Visible = True
        .Activate

       .Documents.Add
    End With
End If
  

Комментарии:

1. Используйте сценарии. Вместо этого FileSystemObject . у него есть хорошая функция FileExists(). Намного чище, чем при использовании старой функции Dir .

2. @JoeBourne: Конечно, но вам не нужно загружать ссылки для использования Dir , поэтому гораздо проще поделиться с другими! 😉

3. оп поздно связывает «Слово. Приложение » so может легко поздно привязать сценарий. filesystemobject также — нет реальной необходимости добавлять ссылку, но ее лениво не делать.

  • #1

Hello all,

I have been reading this forum for years and have found much helpful information, so I am hoping that someone can help me out here. I’ve tried other solutions I found here to no effect.

What I am trying to do is provide a method for users to edit reports that are generated by an application my team developed. In order to provide the flexibility we need, the code first builds the name of the file to be opened using a string variable. Then we would open the Word document… but it keeps giving a Run-Time Error 5174 and stating that it can’t find the file.

I’ve run Debug.Print to output the string that was created and it matches character for charater with the path and file name of the report I want to open. The report exists… it just won’t open.

Here is the code we are using:

Code:

Set appMS_Word = CreateObject("Word.Application")

For Each vSelected_Iterations In colSelected_Iterations
    
With wkbData_Workbook.Sheets("Report Data")
        sReport_Name = .Range("B6").Value
        sReport_Name = sReport_Name & "ReportsExtraction Reports"
        sReport_Name = sReport_Name & .Range("B1").Value
        sReport_Name = sReport_Name & "_Extraction Report Iteration "
        sReport_Name = sReport_Name & vSelected_Iterations & ".docx"
End With
    
appMS_Word.Documents.Open Filename:=sReport_Name, Format:=wdOpenFormatAuto

Next vSelected_Iterations

I’ve even tried copying the path and file name directly from Windows Explorer and it won’t work… anything you can see?

Pivot Table Drill Down

Double-click any number in a pivot table to create a new report showing all detail rows that make up that number

  • #2

My apologies, I realized I did not post the relevant Excel and Windows version information. The application runs in Windows 7 64-bit using Excel 2010 32-bit. Thank you!

RoryA

RoryA

MrExcel MVP, Moderator


  • #4

Just a value. It’s a 6 digit identification number.

RoryA

RoryA

MrExcel MVP, Moderator


  • #5

Just a value. It’s a 6 digit identification number.

Then you appear to be missing at least the Drive information from the file path.

Понравилась статья? Поделить с друзьями:
  • Vba вызов ошибки
  • Vba вывод ошибки
  • Vba вывести сообщение об ошибке
  • Vba word обработка ошибок
  • Vba msgbox ошибка