Я проработал ваш код, но ничего не могу поделать, кроме как подтвердить то, что GSerg уже сказал в своем первом комментарии, т.е. вы не можете закрыть файл, который не открыт.
Option Explicit
Sub Main()
Dim SourceFolder As String
Dim Fn As String ' Filoe name
Dim i As Integer
With Application.FileDialog(msoFileDialogFolderPicker)
If .Show = -1 Then ' if OK is pressed
SourceFolder = .SelectedItems(1)
End If
End With
If SourceFolder <> "" Then ' a folder was chosen
i = 2
Fn = Dir(SourceFolder & "\*.csv")
Do While Len(Fn) > 0
readdatavcap1 Fn, i
Fn = Dir
Loop
End If
End Sub
Private Sub readdatavcap1(filename As String, i As Integer)
' "filename" is a variable used by VBA
' your use of it may cause unexpected problems.
' to check, select the name and press F1.
Dim sl As String
Dim first As Integer
Dim second As Integer
Dim j As Long
Dim fs2 As New Scripting.FileSystemObject
Dim o_file As Scripting.TextStream
Dim tddb_vramp As Boolean
If Dir(filename) <> "" Then
Application.ScreenUpdating = False
j = 2 'variable not defined at fs2
' FileSystemObject also called as FSO, provides an easy object based model
' to access computer's file system.
Set fs2 = CreateObject("Scripting.FileSystemObject")
' o_file contains filename (csv file link)
' 1=Open a file for reading only. You can't write to this file.
' 2=ForWriting, 8= For appending
' TristateFalse means u get ascii file by default.
Set o_file = fs2.OpenTextFile(filename, 1, TristateFalse)
' o_file contains filename(text file data)
' Reads an entire line (up to, but not including, the newline character)
' from a TextStream file and returns the resulting string.
sl = o_file.readline
Do While Left(sl, 1) = "#"
' Left Function is used to extract N number of characters from a string from the left side.
sl = o_file.readline
Loop
' atendofstream = Read-only property that returns True if the file pointer
' is at the end of a TextStream file; False if it is not.
Do While o_file.atendofstream <> True
sl = o_file.readline
' INSTR function returns the position of the first occurrence of a substring in a string.
' syntax of InStr( [start], string, substring, [compare] )
' start sets string position for each search, string = string being search,
' substring= string expression searched ,
' eg:InStr(1, "Tech on the Net", "t") Result: 9
' Shows that search is case-sensitive
' compare= optional 1= textcompare
' searching for commas in the file in this case
first = InStr(32, sl, ",", 1) - 15 ' what if first is negative?
second = InStr(first + 2, sl, ",", 1)
If second = 0 Then
second = Len(sl) + 1 'len=length of file string
End If
' "ActiveWorkbook" seems not necessary unless you intend to have
' several workbooks, all having a sheet "Ramp_current" open at the
' same time, and none of them being ThisWorkbook.
' But if that's your intention "ActiveWorkbook" will lead to
' disaster sooner rather than later.
If tddb_vramp = True Then
' write the Voltage Ramp to stress part
If i = 2 Then
ActiveWorkbook.Sheets("Ramp_current").Cells(j, 1) = Mid(sl, 2, first - 2)
End If
ActiveWorkbook.Sheets("Ramp_current").Cells(j, i) = Abs(Mid(sl, first + 2, second - 2 - first)) + 0.000000000000001
Else
'Write the normal current trace
ActiveWorkbook.Sheets("currentPTN_STI").Cells(j, 2 * i - 3) = Mid(sl, 15, first - 14)
' The MID function returns the specified number of characters in a text string,
' starting from a specified position (ie. starting from a specified character number).
' Use this function to extract a sub-string from any part of a text string.
' Syntax: MID(text_string, start_number, char_numbers).
ActiveWorkbook.Sheets("currentPTN_STI").Cells(j, 2 * i - 2) = Abs(Mid(sl, first + 2, second - 2 - first)) + 0.000000000000001
End If
j = j + 1
Loop
If tddb_vramp = False Then
myarray(i) = j - 1
End If
o_file.Close
Application.ScreenUpdating = True
Else
' if Dir(filename) = "" The o_file doesn't exist
MsgBox filename & " wasn't found.", _
vbInformation, "Reading failure"
End If
End Sub
Вы должны удалить условие Else
из приведенного выше кода. Если вы сделаете это, код ничего не сделает, если файл не найден. Этот факт, вероятно, побудит меня преобразовать эту процедуру в функцию, которая возвращает True, если файл был найден, и False, если это не так. Возможно, это полезно.
Дело в том, что эта процедура должна вызываться Main
pro c, который просматривает все файлы в папке (например), вызывая вашего pro c с другим файлом имена. Таким образом, если ваш профессионал c возвращает False, Main
может выдать сообщение о том, что файл не найден. Но даже если вам это не важно, Main
выберет следующий файл после того, как он найден и оценен или нет.