Within the code attached below, macro opens .csv with values separated by semicolon and comma (at least it looks like it\'s doing so), despite comma speparator set to false and
Thanks to @Ahmed AU answer and comments above I edited my code so it seems to work now. It is supposed to work with .csv and .xlmx files. Here is a bit longer version of the code:
Sub FixCSV()
Dim wrk As Workbook
Dim Sh As Worksheet
Dim findMatch As Range, searchInColumn As Range
Dim i As Long, j As Long, k As Long, lastRow As Long, lastColumn As Long
Dim chosenFile As Integer
Dim xlFileName As String
Dim chooseFiles As Office.FileDialog
Set chooseFiles = Application.FileDialog(msoFileDialogFilePicker)
With chooseFiles
.AllowMultiSelect = True
.Title = "Please select the file."
.InitialFileName = "c:\"
.InitialView = msoFileDialogViewList
.Filters.Add "All", "*.*"
End With
If chooseFiles.Show = -1 Then
For k = 1 To chooseFiles.SelectedItems.Count
xlFileName = chooseFiles.SelectedItems(k)
If InStr(1, xlFileName, ".csv") Then
TmpFlName = path & "TmpCsv.txt"
If Dir(TmpFlName) <> "" Then Kill TmpFlName
FileCopy xlFileName, TmpFlName
Workbooks.OpenText FileName:=TmpFlName, origin:= _
1250, StartRow:=1, DataType:=xlDelimited, TextQualifier:=xlDoubleQuote, _
ConsecutiveDelimiter:=False, Tab:=False, Semicolon:=True, Comma:=False _
, Space:=False, Other:=False, TrailingMinusNumbers:=True, Local:=False
Set wrk = Application.Workbooks("TmpCsv.txt")
Set Sh = wrk.Worksheets(1)
Else
Set wrk = Application.Workbooks.Open(xlFileName)
Set Sh = wrk.Worksheets(1)
End If
lastRow = Sh.Cells(Sh.Rows.Count, "A").End(xlUp).Row
lastColumn = Sh.Cells(1, Sh.Columns.Count).End(xlToLeft).Column
i = 2
Do Until i = lastRow
'do something
Loop
If InStr(1, wrk.Name, "TmpCsv.txt") Then
wrk.SaveAs FileName:=xlFileName, FileFormat:=xlCSV, Local:=True
wrk.Close False
Kill TmpFlName
Else
wrk.Close 'savechanges:=true
End If
Next k
End If
End Sub
While saving as .csv, commas popped up as separators, destroying the file again - this answer by user2726096: https://stackoverflow.com/a/18492514/10348607 helped me to solve the issue.
There are issues with your code as commented by @Tim Williams and @Nick.McDermaid. It is not clear what you want to achieve. However regarding opening Semicolon Delimited text file you may rename the file to .txt
and open like
xlFileName = chooseFiles.SelectedItems(k)
TmpFlName = Path & "TmpCsv.txt"
If Dir(TmpFlName) <> "" Then Kill TmpFlName
FileCopy xlFileName, TmpFlName
Workbooks.OpenText Filename:=TmpFlName, Origin:= _
1250, StartRow:=1, DataType:=xlDelimited, TextQualifier:=xlDoubleQuote, _
ConsecutiveDelimiter:=False, Tab:=False, Semicolon:=True, Comma:=False _
, Space:=False, Other:=False, TrailingMinusNumbers:=True, Local:=False
issue was delimiter option will only work when .txt
file is used not .csv
.