2016-10-05 312 views
1

ファイルがディレクトリに存在するかどうかを確認する必要があります。ファイルがディレクトリに存在しない場合、実行時エラー5174をExcelで処理する方法は?

ファイルが存在しない場合は、新しいファイルを作成する必要があります。

ただし、実行時に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") & "\Desktop\Report.docx" 
Set wrdDoc = wdvar.Documents.Open(FileName) 

With wdvar 
    .Visible = True 
    .Activate 


    .Documents.Add 

答えて

0

エラー処理は次のように行うことができます。

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") & "\Desktop\Report.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: さらに、整数を使用せず、長い変数を使用し、各変数を別々の行に宣言します。それ以外の場合は、変数として宣言します。

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

     .Documents.Add 
    End With 
End If 
+0

優れたソリューション – Prabhu

0

Personnaly、私はこの関数を使用します。 ファイルが存在するかどうかをテストするのに便利な便利な "FileExists()"関数があります。

Dim fso as new Scripting.FileSystemobject 

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

代わりにScripting.FileSystemObjectを使用してください。それは素敵なFileExists()関数を持っています。古いDir関数を使用するよりもはるかにクリーンです。 –

+0

@JoeBourne:もちろんですが、 'Dir'を使うために参照を読み込む必要がないので、他の人と共有する方がはるかに簡単です! ;) – R3uK

+0

Opは "Word.Application"をレイトバインドしているので、scripting.filesystemオブジェクトも簡単に後でバインドすることができます。実際には参照を追加する必要はありません。 –

1

は、Microsoftスクリプトランタイムへの参照を追加し、Scripting.FileSystemObjectオブジェクトを使用します。あなたはそれを使用する必要があります

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 

関連する問題