I would like to know how to import any .csv or .txt file with an input box selection through vba on an existing worksheet named "Raw Data" into row 2, then the filename that was selected will be in cell A1?
I would like to know how to import any .csv or .txt file with an input box selection through vba on an existing worksheet named "Raw Data" into row 2, then the filename that was selected will be in cell A1?
Hello Jagra and welcome to the Forum
Your sub is not named above (and please use the "Add Link" button above in future when supplying code) so I have used the modified code below to add a file name to A1 of worksheet Raw and paste the file contents from A2 down (as per your question).
There are just a few changes to your code (in bold- with alternatives for A1 contents):
Sub ImportCSVorTXT()
Dim fileToOpen As Variant
Dim fileFilterPattern As String
Dim wsMaster As Worksheet
Dim wbTextImport As Workbook
Application.ScreenUpdating = False
fileFilterPattern = "Text Files (*.txt; *.csv), *.txt; *.csv"
fileToOpen = Application.GetOpenFilename(fileFilterPattern)
If fileToOpen = False Then
MsgBox "No file selected"
Else
Workbooks.OpenText _
Filename:=fileToOpen, _
StartRow:=2, _
DataType:=xlDelimited, _
Comma:=True
Set wbTextImport = ActiveWorkbook
Set wsMaster = ThisWorkbook.Worksheets("Raw")
wsMaster.UsedRange.Clear ' clear previous contents
wbTextImport.Worksheets(1).UsedRange.Copy wsMaster.Range("A2")
wbTextImport.Close False
wsMaster.Range("A1").Value = Right(fileToOpen, Len(fileToOpen) - InStrRev(fileToOpen, "\")) ' add filename
'wsMaster.Range("A1").Value = fileToOpen 'OR use the full path and filename
wsMaster.Range("A1").Font.Bold = True
End If
End Sub
The application requestor GetOpenFilename actually delivers your string variable fileToOpen as the full path to the chosen file. I've used string manipulation to extract just the actual file name (but the adjacent commented-out line gives the full path, if that's what you want).
I notice that you use StartRow:=2 in the import (which will exclude the first row/line of a file) but I'd suggest StartRow:=1 so you get the whole file (stated in A1) unless all your files have common headers.
Hope this works for you.