I have an Excel file, in the first sheet I have on column A some text delimited by a separator, like this:
Column A
--------
Text line 1.1
Text line 1.2
Text line 1.3
***
Text line 2.1
Text line 2.2
Text line 2.3
***
Text line 3.1
I like to split the content after the *** separator and put each piece in a separate file with only one sheet. The name of the files should be the first line of the each section.
I need to be able to copy with the formatting, colors, etc.
This is the function but is not copying the formatting...
Private Function AImport(ThisWorkbook As Workbook) As Boolean
Dim height As Long
Dim fileName As String
Dim startLine As Long
Dim endLine As Long
Dim tmpWs As Worksheet
Dim AnError As Boolean
With ThisWorkbook.Worksheets(1) 'sheet name "Sheet1"
height = .Cells(.rows.Count, 2).End(xlUp).row
startLine = 6
nr = 1
For i = startLine + 1 To height
If InStr(.Cells(i, 2).Value, "***") > 0 Then
separate = i
a = Format(nr, "00000")
fileName = "File" & a
endLine = separate - 1
.rows(startLine & ":" & endLine).Copy
Set tmpWs = ThisWorkbook.Worksheets.Add
tmpWs.Paste
tmpWs.Select
tmpWs.Copy
Application.DisplayAlerts = False
ActiveWorkbook.SaveAs fileName:=ThisWorkbook.path & "\Output\" & fileName & " .xls", FileFormat:=xlExcel8, CreateBackup:=False 'xlOpenXMLWorkbookMacroEnabled
ActiveWorkbook.Close
tmpWs.Delete
'update next start line
startLine = separate + 1
nr = nr + 1
End If
Next i
End With
If AnError Then
MsgBox "Errors detected in " & ThisWorkbook.Name & "! Check LogFile.txt file for details. Execution stopped!", vbExclamation, inputWb.Name
AImport = False
Else:
Application.StatusBar = "Workbook check succesfully completed. Executing macro..."
AImport = True
End If
ThisWorkbook.Close
End Function
Just give out a workable solution, surely not a good one
Sub testing()
Dim height As Long
Dim fileName As String
Dim startLine As Long
Dim endLine As Long
Dim tmpWs As Worksheet
With ThisWorkbook.Worksheets("Sheet2") ' Input your sheet name here
height = .Cells(.Rows.Count, 1).End(xlUp).Row
startLine = 3
For i = 2 To height
If InStr(.Cells(i, 1).Value, "***") > 0 Then
separate = i
fileName = .Cells(startLine, 1).Value
endLine = separate - 1
.Rows(startLine & ":" & endLine).Copy
Set tmpWs = ThisWorkbook.Worksheets.Add
tmpWs.Paste
tmpWs.Select
tmpWs.Copy
Application.DisplayAlerts = False
' in the following line, replace the file path with your own
ActiveWorkbook.SaveAs fileName:="H:\" & fileName & " .xlsm", FileFormat:=xlOpenXMLWorkbookMacroEnabled, CreateBackup:=False
ActiveWorkbook.Close
tmpWs.Delete
'update next start line
startLine = separate + 1
End If
Next i
'handline the last section here
endLine = height
fileName = .Cells(startLine, 1).Value
.Rows(startLine & ":" & endLine).Copy
Set tmpWs = ThisWorkbook.Worksheets.Add
tmpWs.Paste
tmpWs.Select
tmpWs.Copy
Application.DisplayAlerts = False
ActiveWorkbook.SaveAs fileName:="H:\" & fileName & " .xlsm", FileFormat:=xlOpenXMLWorkbookMacroEnabled, CreateBackup:=False
ActiveWorkbook.Close
tmpWs.Delete
End With
End Sub
Something like this
This code dumps the files to single sheet csv files under a directory held by strDir, "C:temp" in this example
Sub ParseCOlumn()
Dim X
Dim strDir As String
Dim strFName As String
Dim strText As String
Dim lngRow As Long
Dim lngStart As Long
Dim objFSO As Object
Dim objFSOFile As Object
Set objFSO = CreateObject("scripting.filesystemobject")
strDir = "C:\temp"
X = Application.Transpose(Range([a1], Cells(Rows.Count, "A").End(xlUp)))
'test for first record not being "***"
lngStart = 1
If X(1) <> "***" Then
strFName = X(1)
lngStart = 2
End If
For lngRow = lngStart To UBound(X)
If X(lngRow) <> "***" Then
If Len(strText) > 0 Then
strText = strText & (vbNewLine & X(lngRow))
Else
strText = X(lngRow)
End If
Else
Set objFSOFile = objFSO.createtextfile(strDir & "\" & strFName & ".csv")
objFSOFile.write strText
objFSOFile.Close
strFName = X(lngRow + 1)
lngRow = lngRow + 1
strText = vbNullString
End If
Next
'dump last record
If X(UBound(X)) <> "***" Then
Set objFSOFile = objFSO.createtextfile(strDir & "\" & strFName & ".csv")
objFSOFile.write strText
End If
objFSOFile.Close
End Sub
Related
How can I change the separator that a CSV file is exported with in VBA without changing regional settings etc?
The macro should be used across multiple computers and different users, I don't want to confuse people with changing global settings on their computers.
Is there any way to use another separator?
This is my current code, but the values are separated with commas, I want semicolons
Sub ExportToCSV()
'Variables--------------------------------------------------------------
Dim CSVFileName As String
Dim sheet As Integer
Dim WsData As Worksheet
Set WsData = Worksheets("Database")
'-----------------------------------------------------------------------
WsData.Range(WsData.Cells(7, 9), WsData.Cells(7, 2).End(xlDown)).Copy
Application.DisplayAlerts = False 'avoid "save prompt window"
' Disable screen updating to improve performance
Application.ScreenUpdating = False
Workbooks.Add
ActiveSheet.Paste
' Convert the first row to lowercase
For Each cell In Range("A1:H1")
cell.Value = LCase(cell.Value)
Next cell
CSVFileName = ThisWorkbook.Path & "\" & "Database_" & VBA.Format(VBA.Now, "dd-mm-yy") & ".csv"
ActiveSheet.SaveAs Filename:=CSVFileName, FileFormat:=xlCSV, CreateBackup:=False
ActiveWorkbook.Close
' Enable screen updating again
Application.ScreenUpdating = True
Application.DisplayAlerts = True
End Sub
Note: there could be commas inside the data it is copying.
Any help is greatly appreciated, thank you.
Option Explicit
Sub exportcsv()
Const SHT_NAME = "Database"
Const HDR = 7
Const DELIM = ";"
Dim wb As Workbook, ws As Worksheet, arData
Dim oFSO As Object, oFS As Object
Dim c As Long, i As Long, n As Long, iLastrow As Long
Dim CSVFilename As String, s As String, quote As String
Dim t0 As Single: t0 = Timer
' create text file
Set wb = ThisWorkbook
CSVFilename = wb.Path & "\" & "Database_" & VBA.Format(VBA.Now, "dd-mm-yy") & ".csv"
Set oFSO = CreateObject("Scripting.FileSystemObject")
Set oFS = oFSO.CreateTextFile(CSVFilename, True, True) 'overwrite, Unicode
' write out lines
Set ws = wb.Sheets(SHT_NAME)
With ws
iLastrow = .Cells(Rows.count, "B").End(xlUp).Row
' copy to array
arData = .Range("B1:I1").Offset(HDR - 1).Resize(iLastrow - HDR + 1) ' col 2-9
For i = 1 To UBound(arData)
s = ""
For c = 1 To UBound(arData, 2)
' header
If i = 1 Then arData(i, c) = LCase(arData(i, c))
' add quotes if special chr in value
If arData(i, c) Like "*[;""]*" Then
quote = Chr(34) ' "
Else
quote = ""
End If
' change " to ""
arData(i, c) = Replace(arData(i, c), Chr(34), Chr(34) & Chr(34))
If c > 1 Then s = s & DELIM
s = s & quote & arData(i, c) & quote
Next
oFS.writeline s
n = n + 1
Next
End With
oFS.Close
MsgBox n & " lines written to " & CSVFilename, _
vbInformation, Format(Timer - t0, "0.0 secs")
End Sub
I inherited VBA code that has not worked since my work updated our version of Excel.
The original code looped through all Excel files in a specific folder.
If data in specific cells was blank or a 0, would rename the whole workbook so I would know what files to delete after the fact.
This is the original code. I don't need it to do all of this anymore.
This is part one:
Sub AllFilesWeekly()
Dim folderPath As String
Dim filename As String
Dim wb As Workbook
folderPath = "C:\Users\" & (Environ$("Username")) & "\Desktop\Process Production\" 'change to suit
If Right(folderPath, 1) <> "\" Then folderPath = folderPath + "\"
filename = Dir(folderPath & "*.xlsx")
Do While filename <> ""
Application.ScreenUpdating = False
Set wb = Workbooks.Open(folderPath & filename)
'Call a subroutine here to operate on the just-opened workbook
Call getmetrics
On Error Resume Next
If Not ActiveWorkbook.Name Like "Audit Hub Report Distribution*" Then
ActiveWorkbook.Close
End If
filename = Dir
Loop
Application.ScreenUpdating = True
End Sub
The second part:
Sub getmetrics()
Dim cell As Range
Dim procstring As String, wbname As String
'Dim OQAYTD As String
Dim OQAMTD As String
Dim ORLYTD As String
Dim ORLMTD As String
Dim DR As String
Dim Audits As Long
Dim permonth As String, peryear As String, permonthrl As String, peryearrl As String
Dim RS As Worksheet, AD As Worksheet, QD As Worksheet, ws As Worksheet, YN As Boolean
For Each ws In Worksheets
If ws.Name = "Audit Detail" Then
YN = True
End If
Next ws
If YN = True Then
ActiveWorkbook.Sheets(2).Name = ("Rep Summary")
Set RS = ActiveWorkbook.Sheets("Rep Summary")
Set AD = ActiveWorkbook.Sheets("Audit Detail")
Set QD = ActiveWorkbook.Sheets("Question Detail")
With Sheets("Process Summary")
For Each cell In Range(Range("A3"), Range("A9999").End(xlUp))
If cell.Value = "Record Level YTD" Then
ORLYTD = Range(cell.Address).Offset(0, 1).Value
Else
If cell.Value = "YTD Quality Average" Then
OQAYTD = Range(cell.Address).Offset(0, 1).Value
Else
If cell.Value = "Record Level Quality Average" Then
ORLMTD = Range(cell.Address).Offset(0, 1).Value
Else
If cell.Value = "Quality Average" Then
OQAMTD = Range(cell.Address).Offset(0, 1).Value
Else
If cell.Value = "Audits" Then
Audits = Range(cell.Address).Offset(0, 1).Value
End If
End If
End If
End If
End If
Next cell
End With
wbname = Left(ActiveWorkbook.Name, Len(ActiveWorkbook.Name) - 4)
peryear = VBA.Format(OQAYTD, "Percent")
permonth = VBA.Format(OQAMTD, "Percent")
peryearrl = VBA.Format(ORLYTD, "Percent")
permonthrl = VBA.Format(ORLMTD, "Percent")
DR = Right(Sheets("Process Summary").Range("A2").Value, Len(Sheets("Process
Summary").Range("A2").Value) - 12)
RS.Range(RS.Range("A1"), RS.Range("IV1").End(xlToLeft)).AutoFilter
RS.Range(RS.Range("A1"), RS.Range("IV1").End(xlToLeft)).EntireColumn.AutoFit
AD.Range(AD.Range("A1"), AD.Range("IV1").End(xlToLeft)).AutoFilter
AD.Range(AD.Range("A1"), AD.Range("IV1").End(xlToLeft)).EntireColumn.AutoFit
QD.Range(QD.Range("A1"), QD.Range("IV1").End(xlToLeft)).AutoFilter
QD.Range(QD.Range("A1"), QD.Range("IV1").End(xlToLeft)).EntireColumn.AutoFit
Application.DisplayAlerts = False
procstring = wbname & "|" & permonth & "|" & Audits & "|" & peryear & "|" & permonthrl & "|" &
peryearrl & "|" & DR ' & "|" & Users
Debug.Print procstring
Else
Application.DisplayAlerts = False
Dim AWN As String
AWN = ActiveWorkbook.FullName
Debug.Print "Not Audited: " & ActiveWorkbook.Name
ActiveWorkbook.SaveAs "C:\Users\" & (Environ$("Username")) & "\Desktop\Process Production\Delete -" & Second(Now)
Kill AWN
ActiveWorkbook.Close savechanges:=True
Application.DisplayAlerts = True
End If
End Sub
All I need to do is look at cell D3 on the "Process Summary" tab.
If the value in that space is "0.00%", rename the workbook to delete and loop on until all workbooks are looked at.
I do not need to screen print all the extra numbers any more.
Build a Collection of filenames that match the criteria and then use it to rename the files.
Option Explicit
Sub AllFilesWeekly()
Dim folderPath As String, filename As String
Dim wb As Workbook, ws As Worksheet
Dim col As Collection, n As Long
Set col = New Collection
folderPath = "C:\Users\" & (Environ$("Username")) & "\Desktop\Process Production\" 'change to suit
If Right(folderPath, 1) <> "\" Then folderPath = folderPath + "\"
' scan folder
filename = Dir(folderPath & "*.xlsx")
Do While filename <> ""
Set wb = Workbooks.Open(folderPath & filename, True, True) ' update links, readonly
For Each ws In wb.Sheets
If ws.Name = "Process Summary" Then
If Format(ws.Range("D3"), "0.00%") = "0.00%" Then
col.Add wb.Name
End If
End If
Next
wb.Close
n = n + 1
filename = Dir
Loop
' result
MsgBox "Files scanned = " & n & vbCrLf & _
"To delete = " & col.Count, vbInformation, folderPath
' rename
If col.Count > 0 Then
If MsgBox("Continue to rename ?", vbYesNo) = vbYes Then
For n = 1 To col.Count
Name folderPath & col(n) As folderPath & "delete_" & col(n)
Next
MsgBox "Rename done"
End If
End If
End Sub
I have an inventory list for tools. The point of this program is to search for tools based on tool number entered and based on tool information to locate the corresponding tool file in the specific folder. The name of the files contain part of the tool information.
I loop through the inventory list first, once locating a specific tool, retriving corresponding information and trying to match with the file names within the folder. Here I created another loop to go through the files.
Sub openBaseline(tn)
Dim objFSO As Object
Dim objFolder As Object
Dim objFile As Object
Dim intpath As String
Dim path As String
Dim pn As String
Dim ps As String
Dim varr()
Dim partnum As String
Dim toolsize As String
Dim toolnumber As String
Dim i As Integer
'Testing If Me.idBox.Value = "" And Me.beadBox.Value = "" And Me.partBox.Value = "" Then Exit Sub
If tn = "" Then tn = InputBox("Scan or enter tool number.", "Load Baseline", "")
If tn = "" Then Exit Sub
'If Right(Left(tn, 2), 1) <> "-" Then
'If Len(tn) = 5 Then
'tn = Left(tn, 1) & "-" & Right(tn, 4)
'Else:
'MsgBox "Tool numbers should be in the format of '1-1234'", vbOKOnly + vbExclamation, "Error"
'Exit Sub
'End If
'End If
toolnumber = tn
'Debug.Print toolnumber
With ThisWorkbook.Sheets("Tool Log")
intpath = "H:\PROCESS\PROCESS SAMPLES\SI-Baselines\JSP" 'Switch to \woodbridge.corp etc
Set objFSO = CreateObject("Scripting.Filesystemobject")
Set objFolder = objFSO.getfolder(intpath)
'For Each objFile In objFolder.Files
'varr = Split(objFile.Name, " ")
'ReDim Preserve filename(objFolder.Files.count, 2)
For i = 2 To .Cells(Rows.count, 1).End(xlUp).row Step 1
'Debug.Print .Cells(Rows.count, 1).End(xlUp).row
Debug.Print .Cells(i, "A")
If .Cells(i, 1).Text = toolnumber Then
Debug.Print i
pn = .Cells(i, 3).Value
ps = .Cells(i, 4).Value
Debug.Print pn
Debug.Print ps
End If
'i = 1
For Each objFile In objFolder.Files
Debug.Print objFile.Name
'Debug.Print objFile.path
varr() = Split(objFile.Name, " ")
partnum = varr(0)
toolsize = varr(1)
Debug.Print partnum
Debug.Print toolsize
path = objFile.Name
'Does not work for family tools
Select Case toolsize
Case Is = ps
If partnum = pn Then
Workbooks.Open filename:=objFile.path, UpdateLinks:=False, ReadOnly:=True
Exit For
End If
Case Is = Right(varr(1), Len(varr(1)) - 1)
If partnum = pn Then
Workbooks.Open filename:=objFile.path, UpdateLinks:=False, ReadOnly:=True
Exit For
End If
End Select
Next objFile
'And toolsize = Right(ps, Len(ps) - 1) Then
'path = objFile.Name
'path = Right(path, Len(path) - Len(pn) - 1)
'If Left(path, Len(ps)) = ps Then
'Workbooks.Open filename:=objFile.path, UpdateLinks:=False, ReadOnly:=True
'Exit For
'End If
'End If
'i = i + 1
Next i
End With
End Sub
It gives a Type mismatch error on line
varr() = Split(objFile.Name, " ")
Declare you array variable as array of String (preferable) or as a single Variant, but not as an array of Variant
Also, you should omit the brackets when assigning the result of the split-command.
Dim varr() as String
' or: Dim varr as Variant
...
varr = Split(objFile.Name, " ")
I would like to say i'm an intermediate user of Excel VBA but i'm struggling with this one.
I have written a script to read a text file and strip out all the information I need and then add it to Worksheet that is named by the text file name and then todays date.
Set WS1 = ActiveWorkbook.Sheets("Home")
myFile = Application.GetOpenFilename()
myFileName = FileNameOf(myFile)
WS1.Copy After:=Sheets(Sheets.Count)
Set WS2 = ActiveSheet
strNewSheetName = myFileName & " - " & Format(Now, "DD-MM-YY")
blnSheetCheck = CheckIfSheetExists(strNewSheetName)
If blnSheetCheck = True Then
blnDeleteSheet = MsgBox("NOTICE:" & vbCrLf & vbCrLf & "This text file has already been added today!!" & vbCrLf & vbCrLf & "would you like to delete the existing one?", vbYesNo + vbCritical)
If blnDeleteSheet = vbYes Then
ActiveWorkbook.Sheets(strNewSheetName).Delete
WS2.Name = strNewSheetName
Else
' Roll the number here
End If
Else
WS2.Name = strNewSheetName
End If
I use this function to check if it exists
Function CheckIfSheetExists(SheetName) As Boolean
CheckIfSheetExists = False
Err.Clear
On Error Resume Next
Set WS99 = Sheets(SheetName)
If Err = 0 Then
CheckIfSheetExists = True
Else
CheckIfSheetExists = False
End If
End Function
When I first wrote the code I was going to add a time to the sheet name but it will sometimes push the name over the 31 character limit.
So I would like some guidance on how I can add a numeric to the end of the sheet name and then repeat the process to see if that sheet name exists and then move it up a number and then check again.
Thank you in advance
Andy
This will name the sheets as, for example:
Test 03-05-18 and then Test 03-05-18_01 up to Test 03-05-18_99.
Update this line to allow more copies:
TempShtName = SheetName & "_" & Format(lCounter, "00")
There's one procedure and two functions in the code:
The first is a copy of your code (with variables declare).
The second figures out the name of the sheet.
The third checks if the sheet exists.
Public Sub Test()
Dim WrkBk As Workbook
Dim WS1 As Worksheet, WS2 As Worksheet
Dim myFile As String
Dim myFileName As String
myFile = Application.GetOpenFilename()
'File name including extension:
'myFileName = Mid(myFile, InStrRev(myFile, "\") + 1)
'File name excluding extension:
myFileName = Mid(myFile, InStrRev(myFile, "\") + 1, InStrRev(myFile, ".") - InStrRev(myFile, "\") - 1)
With ThisWorkbook
Set WS1 = .Sheets("Home")
WS1.Copy After:=.Worksheets(.Worksheets.Count)
Set WS2 = .Worksheets(.Worksheets.Count)
WS2.Name = GetSheetName(myFileName & " - " & Format(Now, "dd-mm-yy"))
End With
End Sub
'Return a numbered sheet name (or the original if it's the first).
Public Function GetSheetName(SheetName As String, Optional WrkBk As Workbook) As String
Dim wrkSht As Worksheet
Dim TempShtName As String
Dim lCounter As Long
If WrkBk Is Nothing Then
Set WrkBk = ThisWorkbook
End If
TempShtName = SheetName
Do While WorkSheetExists(TempShtName)
lCounter = lCounter + 1
TempShtName = SheetName & "_" & Format(lCounter, "00")
Loop
GetSheetName = TempShtName
End Function
'Check if the sheet exists.
Public Function WorkSheetExists(SheetName As String, Optional WrkBk As Workbook) As Boolean
Dim wrkSht As Worksheet
If WrkBk Is Nothing Then
Set WrkBk = ThisWorkbook
End If
On Error Resume Next
Set wrkSht = WrkBk.Worksheets(SheetName)
WorkSheetExists = (Err.Number = 0)
Set wrkSht = Nothing
On Error GoTo 0
End Function
Edit:
To remove illegal characters and keep the sheet name to 31 characters you could add this code in the GetSheetName function just before the TempShtName = SheetName line:
Dim x As Long
Dim sChr As String
Const ILLEGAL_CHR As String = "\/*?:[]"
For x = 1 To Len(SheetName)
sChr = Mid(SheetName, x, 1)
If InStr(ILLEGAL_CHR, sChr) > 0 Then
SheetName = Replace(SheetName, sChr, "_")
End If
Next x
If Len(SheetName) > 28 Then
SheetName = Left(SheetName, 28)
End If
Set WS1 = ActiveWorkbook.Sheets("Home")
myFile = Application.GetOpenFilename()
myFileName = FileNameOf(myFile)
WS1.Copy After:=Sheets(Sheets.Count)
Set WS2 = ActiveSheet
strNewSheetName = myFileName & " - " & Format(Now, "DD-MM-YY")
blnSheetCheck = CheckIfSheetExists(strNewSheetName)
If blnSheetCheck = True Then
blnDeleteSheet = MsgBox("NOTICE:" & vbCrLf & vbCrLf & "This text file has already been added today!!" & vbCrLf & vbCrLf & "would you like to delete the existing one?", vbYesNo + vbCritical)
If blnDeleteSheet = vbYes Then
ActiveWorkbook.Sheets(strNewSheetName).Delete
WS2.Name = strNewSheetName
Else
'======Here's the new bit=================
Dim x as integer
x = 1
Do
strnewsheetname = left(strnewsheetname,30) & x
blnSheetCheck = CheckIfSheetExists(strNewSheetName)
x = x +1
Loop while blnSheetCheck
WS2.Name = strNewSheetName
'=============End of New Bit=============
End If
Else
WS2.Name = strNewSheetName
End If
Technically this will keep looping above 9, but from you've said I don't think this will be a problem
Who can help with this macro?
It's merging csv files into one.
csv files can be more than 500 and its running slow.
By the way it's taiking all data in csv file (2 rows). it will work for me if macro can take just second row from file..
Any ideas?
Option Explicit
Sub ImportCSV65()
Dim strSourcePath As String
Dim strDestPath As String
Dim strFile As String
Dim strData As String
Dim x As Variant
Dim Cnt As Long
Dim r As Long
Dim c As Long
Application.Calculation = xlCalculationManual
Application.ScreenUpdating = False
'Change the path to the source folder accordingly
strSourcePath = Worksheets("Tarpinis").Range("AJ8").Value
If Right(strSourcePath, 1) <> "\" Then strSourcePath = strSourcePath & "\"
strFile = Dir(strSourcePath & "*.csv")
Sheets("+65").Select
Application.ScreenUpdating = False
Do While Len(strFile) > 0
Cnt = Cnt + 1
If Cnt = 1 Then
r = 1
Else
r = Cells(Rows.Count, "A").End(xlUp).Row + 1
End If
Open strSourcePath & strFile For Input As #1
If Cnt > 1 Then
Line Input #1, strData
End If
Do Until EOF(1)
Line Input #1, strData
x = Split(strData, ",")
For c = 0 To UBound(x)
Cells(r, c + 1).Value = Trim(x(c))
Next c
r = r + 1
Loop
Close #1
Name strSourcePath & strFile As strSourcePath & strFile
strFile = Dir
Loop
Application.ScreenUpdating = True
If Cnt = 0 Then _
MsgBox "No CSV files were found...", vbExclamation
Application.ScreenUpdating = False
End Sub
How about the following, it will read the second line from each CSV file in the given folder and write that line in the Sheet +65:
Option Explicit
Sub ImportCSV65()
Dim strSourcePath As String
Dim strDestPath As String
Dim strFile As String
Dim strData As String
Dim x As Variant
Dim Cnt As Long
Dim r As Long
Dim c As Long
Dim counter As Long
Dim ws As Worksheet: Set ws = Sheets("+65")
Application.Calculation = xlCalculationManual
Application.ScreenUpdating = False
counter = 0
'Change the path to the source folder accordingly
strSourcePath = Worksheets("Tarpinis").Range("AJ8").Value
If Right(strSourcePath, 1) <> "\" Then strSourcePath = strSourcePath & "\"
strFile = Dir(strSourcePath & "*.csv")
Do While Len(strFile) > 0
Open strSourcePath & strFile For Input As #1
Do Until EOF(1)
Line Input #1, strData
r = ws.Cells(Rows.Count, "A").End(xlUp).Row + 1
counter = counter + 1
If counter = 2 Then 'counter to get only second line
x = Split(strData, ",")
For c = 0 To UBound(x)
ws.Cells(r, c + 1).Value = Trim(x(c))
Next c
r = r + 1
Exit Do
End If
Loop
Close #1
Name strSourcePath & strFile As strSourcePath & strFile
strFile = Dir
counter = 0 'reset counter before next file
Loop
Application.ScreenUpdating = True
End Sub
The only obvious place that I can see that could be done better is the loop that writes the trimmed values into the cells.
If you must trim each value, then you'll still need to loop through the array and Trim it:
For c = 0 To UBound(x)
x(c) = Trim(x(c))
Next c
But to write to the cells, you can speed things up by writing the array directly to the range:
Cells(r, 1).Resize(1, UBound(x) + 1).Value = x
You might also gain a little bit of time by qualifying the destination sheet, preferably as a With.
So the whole thing would look like this:
Sub ImportCSV65()
Dim strSourcePath As String
Dim strDestPath As String
Dim strFile As String
Dim strData As String
Dim x As Variant
Dim Cnt As Long
Dim r As Long
Dim c As Long
Application.Calculation = xlCalculationManual
Application.ScreenUpdating = False
'Change the path to the source folder accordingly
strSourcePath = Worksheets("Tarpinis").Range("AJ8").Value
If Right(strSourcePath, 1) <> "\" Then strSourcePath = strSourcePath & "\"
strFile = Dir(strSourcePath & "*.csv")
With Sheets("+65")
.Select
Application.ScreenUpdating = False
Do While Len(strFile) > 0
Cnt = Cnt + 1
If Cnt = 1 Then
r = 1
Else
r = .Cells(.Rows.Count, "A").End(xlUp).Row + 1
End If
Open strSourcePath & strFile For Input As #1
If Cnt > 1 Then
Line Input #1, strData
End If
Do Until EOF(1)
Line Input #1, strData
x = Split(strData, ",")
For c = 0 To UBound(x)
x(c) = Trim(x(c))
Next c
.Cells(r, 1).Resize(1, UBound(x) + 1).Value = x
r = r + 1
Loop
Close #1
Name strSourcePath & strFile As strSourcePath & strFile
strFile = Dir
Loop
End With
Application.ScreenUpdating = True
If Cnt = 0 Then _
MsgBox "No CSV files were found...", vbExclamation
Application.ScreenUpdating = False
End Sub
Workbooks.Open Filename:=strSourcePath & strFile, Format:=2
This code will open csv file as excel type.
And get data as variant vlaue and will fill your sheet by variant value.
Sub ImportCSV65()
Dim strSourcePath As String
Dim strDestPath As String
Dim strFile As String
Dim strData As String
Dim Ws As Worksheet, rngT As Range
Application.Calculation = xlCalculationManual
Application.ScreenUpdating = False
'Change the path to the source folder accordingly
strSourcePath = Worksheets("Tarpinis").Range("AJ8").Value
If Right(strSourcePath, 1) <> "\" Then strSourcePath = strSourcePath & "\"
strFile = Dir(strSourcePath & "*.csv")
Set Ws = Sheets("+65")
Application.ScreenUpdating = False
With Ws
Do While Len(strFile) > 0
Workbooks.Open Filename:=strSourcePath & strFile, Format:=2
With ActiveWorkbook.ActiveSheet
vDB = .UsedRange
End With
ActiveWorkbook.Close
Set rngT = .Range("a" & Rows.Count).End(xlUp)(2)
rngT.Resize(UBound(vDB, 1), UBound(vDB, 2)) = vDB
strFile = Dir
Loop
End With
Application.ScreenUpdating = False
End Sub