2012-04-26 80 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:label之前缺少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!干杯,谢谢。 – 2012-04-26 10:50:14

0

您可以通过最初试图运行一些作品排查。如果它没有运行空的With ... End With然后错误在外面。否则,你会知道它在里面。然后在With ... End With中一次添加一行,看看何时弹出错误,然后尝试修改该行。

希望这会有所帮助。