0

Many Many thanks in advance I have a .txt file that contains data that needs to be extracted and placed into respective columns in Excel. I am very much new to VBA coding and tried a lot, but having difficulty in making this work... below shows the code I have thus far but when run, it is working differently. Actually Data needs to be placed in their respective field as sample in the excel. In the Excel file I have already kept the data as how it has to be fetched and filled in the respective headed column.

TYPE;ACCOUNT NUMBER:BANK REFERENCE;BENEFICIARY NAME ;DATE ;AMOUNT ;BENE ACCOUNT NUMBER ;BENE IFSC ;BENE BANK NAME ;REFERENCE ;BENE MAIL ID IMPS;45605104698 ;60062000057200 ;ABCDEF ;12122016;0000000001.00;10304060176 ;STRK0002018;STATE BANK OF INDIA ;5110845 ;abce@gmail.com ;

The code which I am using for extracting this above data and to putting in their respective columns is as below:-

Option Explicit

Sub importTXT()
Dim r As Range, myfile As Variant
Dim qt As QueryTable, i As Integer
Dim del As Range

'where myfile needs to select manually
myfile = Application.GetOpenFilename("All Files (*.*), **.*", _
, "Select TXT file", , False)
If myfile = False Then Exit Sub

'elseif its fixed
'myfile = "D:\sample student file"

Application.ScreenUpdating = False

With ActiveSheet
.Range("E7").CurrentRegion.Cells.Clear
With .QueryTables.Add(Connection:="TEXT;" & myfile, Destination:=.Range("$E$7"))
        .Name = "MST"
        .TextFilePlatform = 437
        .TextFileStartRow = 2
        .TextFileParseType = xlDelimited
        .TextFileTextQualifier = xlTextQualifierDoubleQuote
        .TextFileTabDelimiter = True
        .TextFileColumnDataTypes = Array(1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1)
        .TextFileTrailingMinusNumbers = True
        .Refresh BackgroundQuery:=False
    End With
'delete query tables if found any.
    For Each qt In ActiveSheet.QueryTables
        qt.Delete
    Next qt
'Delete the Data Connections
If .Parent.Connections.Count > 0 Then
    For i = 1 To .Parent.Connections.Count
        .Parent.Connections.Item(i).Delete
    Next i
End If

For Each r In .Range("E7:X" & .UsedRange.Rows.Count)
    If InStr(r, "Title = ") > 0 Then
        r.Offset(, 1) = Mid(r.Value, InStr(r, " ") + 8, InStrRev(r.Value, " "))
        r.Offset(, 2) = Mid(r.Value, InStrRev(r.Value, " ") + 2, Len(r.Value) - InStrRev(r.Value, " ") - 2)
    Else
        If del Is Nothing Then
            Set del = r
        Else
            Set del = Union(del, r)
        End If
    End If
Next
End With
Application.ScreenUpdating = False
End Sub

The sample excel file where data needs to be inserted is as below:-

Excel file where data needs to be inserted

Nick is tired
  • 6,860
  • 20
  • 39
  • 51
  • I must confess that I do not understand too much from your question... So, you try opening a txt file in an Excel sheet using `QueryTables.Add`. Does the content open as you expect? If yes, should we understand that the columns order are different from the necessary ones. Is this understanding correct? If yes, can you supply a correspondence table between the txt file columns and Excel sheet? Is it possible that the txt file to not be all the time in the same positions? If not, the requested correspondence should be done in terms of columns header: txt - E, F, G, H etc. ; xls - G, H, E, F etc. – FaneDuru Feb 02 '21 at 14:46
  • I will leave my office in 10 - 15 minutes. If you clarify the above questions sooner, I can supply a solution, I think... E, F, G, H etc can be expressed like "E:AC". It should be a continuous columns range, anyhow. – FaneDuru Feb 02 '21 at 14:50
  • Please [edit] your question to clarify exactly what is going wrong and/or specifically what "doesn't work" is standing for. If you're getting any errors, include the messages and indicate which instruction is blowing up. If the output isn't as expected, explain how the actual output is different from the expected output. – Mathieu Guindon Feb 02 '21 at 15:08
  • Many Many Thanks FaneDuru, for better understanding I will share you the files. There you will understand full –  Feb 02 '21 at 15:34
  • @FaneDuru, this is last time please have a look –  Feb 04 '21 at 20:07
  • @FaneDuru please check this CSV file https://drive.google.com/file/d/1kXBmS4Ye8tc1IY12qFfhD_vKs3usfbQZ/view?usp=sharing –  Feb 04 '21 at 20:14
  • I am not sure that you know what you want, sorry... Should I understood **now** that your text file to be imported **will have 11 fields/columns**? If yes, why did you send text files containing 20 fields? If not, what the last csv and the sheet "ImportT" do mean? I am waiting no more then 10 minutes for your answer. Then, I must close my laptop. – FaneDuru Feb 04 '21 at 20:21
  • @FaneDuru Actually, we get source file as notepad text in that format only and as of now we have to manually copy and past in our desired 24 fields which is preformatted with headings which you have seen and then again we select those 24 fields particular rows from excel and then paste it in the notepad again with desired 24 fields data which we have copy and pasted as below –  Feb 05 '21 at 12:32
  • @FaneDuru “1452889”;“XYZ”;“45605104698”;“USD”;“IMPS”;“0000000001.00”;“USD”;“12122016”;“5110845”;“60062000057200”;“”;“”;“45869974582”;“ABCDEF”;“”;“”;“”;“”;“STRK0002018”;“”;“”;“abce@gmail.com”;“”;“” –  Feb 05 '21 at 12:32
  • @FaneDuru And then after converting to text file we need to upload this text file in one of our system, cause that system only supports text file. Now, if you have understand then please help me out. Many many thanks again for supporting me. –  Feb 05 '21 at 12:32
  • I did not understand **anything**! I initially thought I could understand a little, but now I am completely confused. Are you able to answer simple questions? If yes, **how many columns will have the text file to be processed by the code you need**? **11, 20 or 24**? **For what number of columns version your matching has been done**? I do not care about the file history... **How many rows should be in such a file (approximatively)**? – FaneDuru Feb 05 '21 at 12:45
  • @FaneDuru, please this last time, if you are not able to understand then I will not ask you again. Please have a look to this below link where I have created a chart to understand you. https://drive.google.com/file/d/1R1SQJePzY23rbObciMJxQHCEKijwr0OL/view?usp=sharing –  Feb 05 '21 at 16:03
  • I am afraid you do not understand **anything** about the logic of the issue... I asked you some questions, but strictly for nothing. Your picture **does not supply any useful information**! How do you imagine that I can use what you "created"? Since the real data will never be the same, what you done is completely useless. You should match **columns of the txt file with columns of the xls sheet**. I asked this in clear, but it looks it is impossible to get logical terms. Even if you did not look to understand what is it about, I tried taking it as a challenge but anything I tried was useless. – FaneDuru Feb 05 '21 at 19:30
  • If you not understand by yourself what is to be supplied, **why don't you try answering my questions**? Was it so difficult to answer what I asked in my last comment? Then to make a **columns match between the text file columns and excel sheet ones**... I simple cannot understand your way of thinking. – FaneDuru Feb 05 '21 at 19:53

1 Answers1

-1

I used a different approach but I think this will do what you need:

  1. import CSV

  2. store it in array

  3. setup array with new col nrs based on mapping array

  4. paste to sheet

     Sub ImportCsv()
         'load the source file based on user input to an array
         Dim filename As String, Data
         filename = Application.GetOpenFilename
         Data = openfile(filename)
    
         'spitting first line to get nr of columns
         Dim cls, Data2, j As Long, i As Long, newcls
         cls = Split(Data(1, 1), ";")
    
         'Re-Order columns - You can just change to nr according to your mapping => first column mapped to col 5 etc...
         newcls = Array(5, 3, 10, 14, 8, 6, 13, 19, 18, 9, 22)
    
         'Setup reformated array, make sure the Ubound of columns corresponds to the max col in your mapping
         ReDim Data2(1 To UBound(Data), 1 To 22)
         For j = 1 To UBound(Data, 1)
             cls = Split(Data(j, 1), ";")
             For i = 1 To UBound(cls)
                 Data2(j, newcls(i)) = Trim(cls(i - 1))
             Next i
         Next j
    
         'paste to sheet
         Worksheets("Sheet1").Range("A1").Resize(UBound(Data2), UBound(Data2, 2)).Value2 = Data2
     End Sub
    
     Private Function openfile(filename As String) As Variant
         'import External
         Dim wbExt As Workbook, Data, FilePath As String
         'FilePath = Application.ActiveWorkbook.Path & filename => alternative if you just ask a filename to the user. this will set the path.
         Set wbExt = Workbooks.Open(filename:=filename) 'replace filename with filepath if you choose above approach
         With wbExt: Data = .Sheets(1).UsedRange.Value: .Close: End With 'get data from source and close
         openfile = Data 'send array back to main sub
     End Function
    

best of luck,

ceci
  • 589
  • 4
  • 14
  • thanks very much for understanding me it works very much fine in csv format, but if possible can it be done directly from note pad to excel. Many many thanks in advance. –  Feb 08 '21 at 10:04
  • Hi Rahul, I don't understand your question. – ceci Feb 08 '21 at 10:52
  • Hi, kindly please download below notepad text from below link https://drive.google.com/file/d/109MZsujuCXyEEvroARVHvTqV5w5k0W6F/view?usp=sharing –  Feb 08 '21 at 15:53
  • this note pad has data with extra spaces. if possible could you please provide only the code through which I can directly import the original all text data into the excel without any extra spaces from notepad text file. Please ignore what I have uploaded initially. –  Feb 08 '21 at 15:56
  • just provide me that when I will click on button then it will load all data all text file data from column A to so on till the end of file and also without extra spaces. –  Feb 08 '21 at 15:58
  • I updated the answer => changed the separator to ";" and added a "TRIM" function before populating the new array => Data2(j, newcls(i)) = Trim(cls(i - 1)) – ceci Feb 08 '21 at 17:08
  • many many thanks, but I stuck that how to get the fileopen dialog box to select the file manually by user –  Feb 08 '21 at 17:29
  • how can i get option to select file manually through open file dialog box. Many many thanks –  Feb 08 '21 at 17:32
  • I added the Application.GetOpenFilename and put the rest as a function. This will not work on MAC! but should make you the new scripting hero at work. best of luck – ceci Feb 08 '21 at 18:22