2012-04-26 9 views
1

次のコードは、ログファイルから重複した行を削除するサブの始まりです。しかし、私がこれまでに行ったことをテストした後、なぜこれが私にエラーを与えているのか理解できません。コードは次のとおりです。VBA - なぜ私にエラーが表示されますか?

Sub cleanUpLogFile() 

Dim logFileStr As String 

Dim newBook As Workbook 
Dim fd1 As FileDialog 

MsgBox "Select your log file.", vbInformation, "Important Info" 
Set fd1 = Application.FileDialog(msoFileDialogFilePicker) 
With fd1 
    .AllowMultiSelect = False 
    .Filters.Clear 
    .Filters.Add "*.xl* Files", "*.xl*", 1 
    'if user selects a file then 
    If .Show Then 
     'assign selection to variable 
     logFileStr = fd1.SelectedItems.Item(1) 
     Else 'display prompt and exit sub 
      MsgBox "You didn't select your indexation file. Exiting...", _ 
       vbCritical, "Important Info" 
      Exit Sub 
    End If 
End With 

Set newBook = Workbooks.Open(logFileStr, 0) 
newBook.Close (0) 
Set newBook = Nothing 

MsgBox "finished" 

errHandler: 
MsgBox "Encountered an error: " & Err.Number & " -> " & Err.Description, _ 
     vbExclamation, "Error! - from cleanUpLogFile() sub" 
Err.Clear 
Exit Sub 
End Sub 

エラーメッセージボックスでも多くの情報がわかりません。 err.Numberは「0」と表示され、err.Descriptionの対応する説明は存在しません。

アイデア?

ありがとう、 QF。

答えて

2

errHandler:ラベルの前にExit Subステートメントがありません。

VBのラベルは実際にはコード内の位置のブックマークにすぎません。そのため、ラベルの下にコードを置く前に関数を終了するには、そのように指示する必要があります。

エラーがない場合でも、errHandler:ラベルの下のコードが実行され、出力には「エラーはありませんでした」と表示されます。あなたが最初に働く何かを実行しようとすることで、トラブルシューティングができ

... more code 
Set newBook = Nothing 

MsgBox "finished" 
Exit Sub 
errHandler: 
MsgBox "Encountered an error: " & Err.Number & " -> " & Err.Description, _ 
     vbExclamation, "Error! - from cleanUpLogFile() sub" 
Err.Clear 
Exit Sub 
End Sub 
+0

Doh!乾杯、ありがとう。 –

0

だから、にあなたのコードを変更します。それが空で実行されない場合... With Endこのエラーは外です。それ以外の場合は、それが内部にあることがわかります。次に、With ... End Withを一度に追加して、エラーがポップアップした時点を確認し、その行を修正してみます。

これが役に立ちます。

関連する問題