«Файл уже открыт» при попытке открыть текстовый файл - PullRequest
0 голосов
/ 28 февраля 2020

Что я хочу сделать: У меня есть Log.txt, где перечислены специальные значения из листа Excel. Каждый раз, когда выполняется макрос, он проверяет наличие новых специальных значений. Перед добавлением их в Log.txt через Sub, тот же Sub проверяет, есть ли соответствующее значение (они однозначны) уже в Списке Журналов. Если это не так, значение должно быть добавлено в список.

Мой подход: Мой текущий подход можно увидеть в примере кода ниже.


Dim FileNum as Integer
dim DataLine as String
Dim strPath as String
Dim strEntry as String

strPath = [Path to Log.txt]  
strEntry = [Special Value]     

'In this first part the Log.txt is opened for Input and each line is saved in DataLine 
'to be compared to the special value in strEntry. If it is already in the Log.txt, the Sub to
'create a new Log-Entry is exited and is started again, once the next special value from another cell is 
'obtained (from another Sub).

FileNum = FreeFile()
Open strPath For Input As #FileNum
Do While Not EOF(FileNum)
     Line Input #FileNum, DataLine
'The value strEntry should start at position 2 of the Entry in the Log.txt (due to the quotation marks [""] in the 
'Log.txt line.
     If InStr(DataLine, strEntry) = 2 Then Exit Sub
     Loop
Close #FileNum

'After it could be verified, that strEntry is not already in the Log.txt, the txt-File should be opened 
'again, this time for Append. Then, the strEntry should be written to the txt-File, the Log.txt should close and 
'Sub is finished.

FileNum = FreeFile()
Open strPath For Append As #FileNum
Write #FileNum, strEntry 
Close #FileNum

Проблема: Я заметил, что первая часть Sub работает нормально. Если strEntry уже находится в Log.txt, Sub завершается, и весь макрос переходит к следующему специальному значению. Если этого значения еще нет в txt-файле, первая часть Sub не выходит из Sub и переходит ко второй части, где следует добавить значение к Log.txt.

Вот в чем проблема. Если я исключу первую часть Sub, я смогу убедиться, что вторая часть также работает нормально (так как он просто добавляет все значения в txt-File). Но как только я включил первую часть, я получаю сообщение об ошибке

Файл уже открыт.

Я не могу понять, почему это происходит, так как я Close #FileNum в конце первой части.

Заранее благодарю за ваши идеи и решения.

1 Ответ

2 голосов
/ 28 февраля 2020

Проблема If InStr(DataLine, strEntry) = 2 Then Exit Sub В этом случае вы не закрываете файл, поскольку он выходит из Sub. В этом случае файл остается открытым. Используйте Exit Sub разумно. Попробуйте использовать одну точку входа и одну точку выхода, чтобы вы могли располагать объекты / переменные и правильно выполнять соответствующую очистку.

В одну сторону : использование логической переменной

'
'~~> Rest of your code
'
Dim continue As Boolean: continue = True

'
'~~> Rest of your code
'

Do While Not EOF(FileNum)
    Line Input #FileNum, DataLine
    If InStr(DataLine, strEntry) = 2 Then
        continue = False
        Exit Do
    End If
Loop
Close #FileNum

If continue = True Then
    FileNum = FreeFile()
    Open strPath For Append As #FileNum
    Write #FileNum, strEntry
    Close #FileNum
End If

Другой способ : Использование GOTO

    FileNum = FreeFile()
    Open strPath For Input As #FileNum
    Do While Not EOF(FileNum)
        Line Input #FileNum, DataLine
        'The value strEntry should start at position 2 of the Entry in the Log.txt (due to the quotation marks [""] in the
        'Log.txt line.
        If InStr(DataLine, strEntry) = 2 Then GoTo CleanupAndExit
    Loop
    Close #FileNum

    'After it could be verified, that strEntry is not already in the Log.txt, the txt-File should be opened
    'again, this time for Append. Then, the strEntry should be written to the txt-File, the Log.txt should close and
    'Sub is finished.

    FileNum = FreeFile()
    Open strPath For Append As #FileNum
    Write #FileNum, strEntry
CleanupAndExit:
    Close #FileNum
...