Sub TestCSV_ExtractData()
Dim destWB As Workbook, csvWB As Workbook
Dim destSht As Worksheet, csvSht As Worksheet
Dim csvRng As Range
Dim csvArr As Variant
Dim iCnt As Long, jCnt As Long, jCntRvrs As Long, jCntMid As Long
Dim jLeft As Long, jRight As Long
Dim strBal As String
Dim outArr() As Variant
Dim outRow As Long, outCol As Long
Dim hdgArr As Variant
Application.ScreenUpdating = False
Set destWB = ThisWorkbook
Set destSht = destWB.Worksheets("JohnnyL")
Dim CSV_FileToOpen As Variant
'
CSV_FileToOpen = Application.GetOpenFilename("Text files,*.csv", , "Select file", , False)
If CSV_FileToOpen = False Then
Exit Sub
End If
Workbooks.Open Filename:=CSV_FileToOpen
Set csvWB = ActiveWorkbook
Set csvSht = csvWB.ActiveSheet
Set csvRng = csvSht.UsedRange
csvArr = csvRng.Value
hdgArr = Array("Txn No", "Txn Date", "Description", "Branch Name", "Cheque No", "Dr Amount", "Cr Amount", "Balance", "Dr/Cr", "Src Row")
ReDim outArr(1 To UBound(csvArr, 1), 1 To 10)
outRow = 1
For iCnt = 1 To UBound(csvArr, 1)
If IsNumeric(Right(csvArr(iCnt, 1), 6)) Then
outCol = 0
For jCnt = 1 To UBound(csvArr, 2)
If csvArr(iCnt, jCnt) <> "" Then
outCol = outCol + 1
outArr(outRow, outCol) = csvArr(iCnt, jCnt)
If outCol = 4 Then
jLeft = jCnt + 1
Exit For
End If
End If
Next jCnt
For jCntRvrs = UBound(csvArr, 2) To jLeft Step -1
If csvArr(iCnt, jCntRvrs) <> "" Then
strBal = csvArr(iCnt, jCntRvrs)
outArr(outRow, 9) = Mid(strBal, Len(strBal) - 2, 2)
outArr(outRow, 8) = Replace(Left(strBal, Len(strBal) - 4), ",", "")
outArr(outRow, 7) = csvArr(iCnt, jCntRvrs - 1)
outArr(outRow, 6) = csvArr(iCnt, jCntRvrs - 3)
jRight = jCntRvrs - 3 - 1
Exit For
End If
Next jCntRvrs
For jCntMid = jLeft To jRight
If csvArr(iCnt, jCntMid) <> "" Then
outArr(outRow, 5) = csvArr(iCnt, jCntMid)
End If
Next jCntMid
outArr(outRow, 2) = Replace(outArr(outRow, 2), "-", "/")
outArr(outRow, 3) = Replace(outArr(outRow, 3), vbLf, " ")
outArr(outRow, 4) = Replace(outArr(outRow, 4), vbLf, " ")
outArr(outRow, 10) = iCnt
outRow = outRow + 1
End If
Next iCnt
With destSht
.UsedRange.Clear
.Range("A1").Resize(, UBound(hdgArr) + 1) = hdgArr
.Range("A1").Resize(, UBound(hdgArr) + 1).Font.Bold = True
.Range("A1").Offset(1).Resize(outRow - 1, UBound(outArr, 2)).Value = outArr
' Convert Date Column to Date
.Range("A1").Offset(1, 1).Resize(outRow - 1).TextToColumns Destination:=.Range("A1").Offset(1, 1), DataType:=xlDelimited, _
TextQualifier:=xlDoubleQuote, ConsecutiveDelimiter:=False, Tab:=True, _
Semicolon:=False, Comma:=False, Space:=False, Other:=False, FieldInfo _
:=Array(1, 4), TrailingMinusNumbers:=True
.Columns("E").NumberFormat = "General" ' Cheque No field
.Range("F:H").EntireColumn.NumberFormat = "_(* #,##0.00_);[Red]_(* (#,##0.00);;_(@_)" ' Amount fields
.UsedRange.Columns.AutoFit
End With
Application.DisplayAlerts = False
csvWB.Close SaveChanges:=False
Application.DisplayAlerts = True
Application.ScreenUpdating = True
End Sub