Reputation: 1
I have a repetitive process which includes importing data from different csv files to excel
Current process Import data manually from data > from text > select the required file > select delimited and my data has headers > select delimiter comma > next > finish > New worksheet
Is there a way to make a vba script/macro which will prompt the user what file they want to import and slect the options which I have selected
Thanks and regards
Upvotes: 0
Views: 546
Reputation: 55
This is some code I used some time ago.
Dirlocal
is the path of the .csv
file
I would have the data imported in a Worksheet named "ODK"
Dim ws As Worksheet
Dim strText As String
' read utf-8 file to strText variable
With CreateObject("ADODB.Stream")
.Open
.Type = 1 ' Private Const adTypeBinary = 1
.LoadFromFile DirLocal
.Type = 2 ' Private Const adTypeText = 2
.Charset = "utf-8"
strText = .ReadText(-1) ' Private Const adReadAll = -1
End With
' parse strText data to a sheet
Set ws = Worksheets("ODK")
intRow = 1
Application.DisplayAlerts = False
For Each strLine In Split(strText, Chr(10))
If strLine <> "" Then
With ws
.Cells(intRow, 1) = strLine
.Cells(intRow, 1).TextToColumns Destination:=Cells(intRow, 1), DataType:=xlDelimited, _
TextQualifier:=xlDoubleQuote, ConsecutiveDelimiter:=False, Tab:=False, _
Semicolon:=False, Comma:=True, Space:=False, Other:=False
End With
intRow = intRow + 1
End If
Next strLine
Application.DisplayAlerts = True
ReadUTF8CSVToSheet = ws.Name
Upvotes: 1
Reputation: 6984
You can use Application.getopenfilename to select the desired file to open. As mentioned in one of the comments, using the macro recorder to get the code to manipulate the data is a good start and you can add it to this code.
Sub Button1_Click()
Dim s, wb As Workbook
s = Application.GetOpenFilename("CSV Files (*.csv),*.csv", , "Please select CSV file...")
If s <> False Then
Set wb = Workbooks.Open(s)
MsgBox "Code to Do something here"
wb.Close False
Else: MsgBox "Nothing Selected"
End If
End Sub
Upvotes: 0