Forum Discussion
MortenK77
Feb 25, 2021Copper Contributor
Import CSV from listbox in userform
I have created a simple userform with a list box. CSV files from a folder are listed in the listbox. I want to select a file from the listbox, and import it to a new sheet1 in the active woorkbook. ...
Subodh_Tiwari_sktneer
Mar 14, 2021Silver Contributor
Please replace all the codes on your UserForm Module with the following codes and let me know if this works as desired.
Code for UserForm Module:
Dim csvFile As String
Private Sub CommandButton1_Click()
Dim swb As Workbook
Dim dws As Worksheet
If csvFile <> "" Then
Set dws = Worksheets.Add
Set swb = Workbooks.Open(csvFile)
Range("A1").CurrentRegion.Copy
dws.Range("A1").PasteSpecial xlPasteAll
swb.Close False
Else
MsgBox "Please select a csv file from the ListBox first and then try again...", vbExclamation, "CSV File Was Not Selected!"
Exit Sub
End If
End Sub
Private Sub UserForm_Initialize()
'Files in folder listed in Listbox1
Dim FSO As Object, fld As Object, Fil As Object
Dim SubFolderName As String
Dim i As Long
With Me.ListBox1
.ColumnCount = 2
.ColumnWidths = "200,0"
End With
Set FSO = CreateObject("Scripting.FileSystemObject")
SubFolderName = "E:\ICP-Smartmål\Ny fil fra ICP"
If FSO.folderexists(SubFolderName) Then
Set fld = FSO.GetFolder(SubFolderName)
For Each Fil In fld.Files
If LCase(FSO.getextensionname(Fil)) = "csv" Then
For i = 0 To 1
With Me.ListBox1
.AddItem
.List(i, 0) = Fil.Name
.List(i, 1) = Fil.Path
End With
Next i
End If
Next Fil
Else
MsgBox "The following Source Folder was not found..." & vbNewLine & vbNewLine & SubFolderName, vbExclamation, "Source Folder Not Found!"
End
End If
End Sub
Private Sub ListBox1_Click()
TextBox1.Text = Me.ListBox1.List(Me.ListBox1.ListIndex, 0)
csvFile = Me.ListBox1.List(Me.ListBox1.ListIndex, 1)
End Sub
- MortenK77Mar 14, 2021Copper ContributorThis code works great, thank you!