Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/excel/28.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
VBA-为什么这会给我一个错误?_Vba_Excel - Fatal编程技术网

VBA-为什么这会给我一个错误?

VBA-为什么这会给我一个错误?,vba,excel,Vba,Excel,下面的代码是从日志文件中删除重复行的子文件的开头,因此得名。然而,在测试了我目前所拥有的东西之后,我无法理解为什么这会给我一个错误。代码如下: Sub cleanUpLogFile() Dim logFileStr As String Dim newBook As Workbook Dim fd1 As FileDialog MsgBox "Select your log file.", vbInformation, "Important Info" Set fd1 = Applicati

下面的代码是从日志文件中删除重复行的子文件的开头,因此得名。然而,在测试了我目前所拥有的东西之后,我无法理解为什么这会给我一个错误。代码如下:

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
错误消息框也没有给我太多信息<代码>错误编号显示为“0”,而
错误描述
中的相应描述不存在

有什么想法吗

谢谢,
QF.

您的errHandler:label前面缺少一个Exit子语句

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

您可以通过最初尝试运行一些有效的工具来进行故障排除。如果它没有以空with…End with运行,则错误在外部。否则你会知道它在里面。然后在With…End With中添加一行,每次查看何时弹出错误,然后尝试修改该行

希望这有帮助