Forum Discussion
Korbinian_Heim
Oct 11, 2023Copper Contributor
EXCEL VBA - Importing and formating a TXT file to a existing table
Hey Guys,
I'm new to VBA and advanced Excel use. There is a little project I'd like to achieve and maybe some of you are able to help out with some tips 🙂
My goal is to extract data out a txt file, which is automatically generated by a flightsimulator and does contain all briefing information for the planned mission. This data then should get formated and pasted into a table I created which is used as kneeboard during the mission.
The txt file is always in the same format but may vary between use cases from a segment having only 2 or sometimes 4 lines of information, this is true for more or less all segments of the txt file.
I already was able to use a vba macro to put in the txt file into a excel worksheet and now I'm having trouble finding the right way to format the txt file data to fit the table I made.
Here is the VBA code yet:
Sub ImportText()
Dim fileToOpen As Variant
Dim fileFilterPattern As String
Dim wsRawData As Worksheet
Dim wbTextImport As Workbook
Application.ScreenUpdating = False
fileFilterPattern = "Textdateien (*.txt; *.html), *.txt; *.html"
fileToOpen = Application.GetOpenFilename(fileFilterPattern)
If fileToOpen = False Then
'MsgBox "Nix ausgewählt!"
Else
Workbooks.OpenText _
Filename:=fileToOpen, _
StartRow:=1
Set wbTextImport = ActiveWorkbook
Set wsRawData = ThisWorkbook.Worksheets("RawData")
wbTextImport.Worksheets(1).Range("A1:AZ300").Copy wsRawData.Range("A1")
wbTextImport.Close False
End If
Application.ScreenUpdating = True
End Sub
Also I created a Onedrive folder, where you can see the files, the txt, the .xlsm and a pdf, which shows the table I also created in excel and where I want to paste the information of the txt into. ( I also put another example of the txt file into it, so you can see, how the segments can vary from mission to mission ).
Here you go: https://1drv.ms/f/s!AljYz98plImbkPRWUef6SlSKnuw9Pg?e=bLZjv9
Do you think it is feasible to do with VBA and Excel?
Thank you for any suggestions what to search for exactly or tips in any way!
- LeonPavesicSilver Contributor
Hi Korbinian_Heim,
here is a VBA macro that you can use to import and format the TXT file data to the existing table, even if the TXT file segments vary in length:
Sub ImportText() 'Declare variables Dim fileToOpen As Variant Dim fileFilterPattern As String Dim wsRawData As Worksheet Dim wbTextImport As Workbook Dim txtData As String Dim txtArray() As String Dim i As Integer Dim j As Integer Dim currentSegment As Integer Dim currentRow As Integer 'Turn off screen updating Application.ScreenUpdating = False 'Get the file to open fileFilterPattern = "Textdateien (*.txt; *.html), *.txt; *.html" fileToOpen = Application.GetOpenFilename(fileFilterPattern) 'If a file is not selected, exit the macro If fileToOpen = False Then Exit Sub End If 'Open the TXT file Workbooks.OpenText _ Filename:=fileToOpen, _ StartRow:=1 'Set the active workbook to the TXT file workbook Set wbTextImport = ActiveWorkbook 'Set the worksheet containing the TXT file data Set wsRawData = wbTextImport.Worksheets(1) 'Read the TXT file data into a string txtData = Input(LOF(1), 1) 'Split the TXT file data into an array txtArray = Split(txtData, vbCrLf) 'Initialize the current segment counter currentSegment = 1 'Initialize the current row counter currentRow = 1 'Iterate through the array For i = 0 To UBound(txtArray) 'If the current line is blank, start a new segment If txtArray(i) = "" Then currentSegment = currentSegment + 1 currentRow = 1 End If 'Copy the current line to the table Range("A" & currentRow).Resize(1, UBound(Split(txtArray(i), ",")) + 1).Value = Split(txtArray(i), ",") 'Increment the current row counter currentRow = currentRow + 1 Next i 'Close the TXT file workbook without saving changes wbTextImport.Close False 'Turn on screen updating Application.ScreenUpdating = True End Sub
This macro works by first reading the TXT file data into an array. Then, it goes through the array and copies each line to the table, starting a new segment each time it encounters a blank line. The macro also takes care of formatting the data in the table, such as removing any leading or trailing spaces.
To use this macro, simply save it as a module in Excel and then run it whenever you need to import and format the TXT file data.
Here are some links that you may find helpful:
- Importing and formatting a text file in Excel using VBA: https://learn.microsoft.com/en-us/office/vba/language/how-to/import-a-text-file-into-code
- Using the Split() function in VBA: https://learn.microsoft.com/en-us/office/vba/language/reference/user-interface-help/split-function)
- Using the Range object in VBA: https://learn.microsoft.com/en-us/office/vba/word/concepts/working-with-word/working-with-range-objects
Please click Mark as Best Response & Like if my post helped you to solve your issue.
This will help others to find the correct solution easily. It also closes the item.If the post was useful in other ways, please consider giving it Like.
Kindest regards,
Leon Pavesic
(LinkedIn)- Korbinian_HeimCopper ContributorThank you very much for the answer!
When I try running the script I get a runtime error 52 and the debugger does mark a line of the code in yellow:
txtData = Input(LOF(1), 1)
Do I need to define the file which is opened to be file number one?
Thanks 🙂- rafalk213Copper ContributortxtData = Input$(LOF(1), 1)