I'm working in a macro that convert CSV to Excel (xlsx). The problem is that, althought the extension change, the new converted file to excel keeps the structure of a CSV file, I mean, not separated by columns.
myFile = Dir(myPath & "*.csv")
Set wb = Workbooks.Open(myPath & myFile)
wb.SaveAs myPath & Replace(myFile, ".csv", ""), xlOpenXMLWorkbook
wb.Close False
Is there something wrong?
Thanks!
Your text file include some characters else of Ansi encoding.
And that need delete "=", quote. That's delimiter is semi-colon.
Line delimiter is ";;;" three semi-colon(my guess).
Sub openCsv()
Dim Wb As Workbook
Dim myPath As String, myFile As String
Dim newFile As String
Dim s As String
Dim vR(), vSplit, vSub
Dim n As Long, i As Long, j As Integer
myPath = ThisWorkbook.Path & "\" 'your path
myFile = "myTest.csv" 'your csv file
newFile = Split(myFile, ".")(0) & ".xlsx"
s = TransFromUtf_8(myPath & myFile)
s = Replace(s, "=", "")
s = Replace(s, Chr(34), "")
vSplit = Split(s, ";;;")
For i = 0 To UBound(vSplit)
n = n + 1
vSub = Split(vSplit(i), ";")
ReDim Preserve vR(1 To 30, 1 To n)
For j = 0 To UBound(vSub)
vR(j + 1, n) = vSub(j)
Next j
Next i
Set Wb = Workbooks.Add
With Wb
With .Sheets(1)
.Cells.NumberFormatLocal = "#"
.Range("a1").Resize(n, 30) = WorksheetFunction.Transpose(vR)
.Columns.AutoFit
End With
.SaveAs myPath & newFile
.Close (0)
End With
End Sub
Function TransFromUtf_8(myFile As String)
Dim objStream
Set objStream = CreateObject("ADODB.Stream")
With objStream
.Charset = "utf-8"
.Open
.LoadFromFile myFile
TransFromUtf_8 = .ReadText
.Close
End With
Set objStream = Nothing
End Function
Related
I have written code for consolidate the data from multiple workbook to one workbook and the code only opening the xls format files but some files have csv format in the folder. how to open csv and xls files in the folder? Any suggestion it would appreciated
Option Explicit
Sub ImportGroups()
Dim fPATH As String, fNAME As String
Dim LR As Long, LastRow As Long
Dim wb2, wb1 As Workbook, ofs As Worksheet
Set ofs = ThisWorkbook.Sheets("Sheet3")
fPATH = "C:\Users\ashokkumar.d\Desktop\MFI\"
fNAME = Dir(fPATH & "*.xls") 'get the first filename in fpath
Do While Len(fNAME) > 0
Set wb1 = Workbooks.Open(fPATH & fNAME) 'open the file
LastRow = ofs.Range("B" & Rows.Count).End(xlUp).Row
ofs.Range("B" & LastRow).Offset(1, -1).Value = fNAME
Sheets("Input").Range("C8:J12").Copy
ofs.Range("B" & LastRow).Offset(1, 0).PasteSpecial xlPasteValues
wb1.Close False 'close data workbook
fNAME = Dir 'get the next filename
Loop
LR = ofs.Range("C" & Rows.Count).End(xlUp).Row
ofs.Range("E2:I" & LR).Select
Selection.NumberFormat = "0.00%"
Application.ScreenUpdating = True
ofs.Range("A1:Z" & LR).Select
With Selection
WrapText = True
End With
End Sub
Just like this:
fNAME = Dir(fPATH & "*") 'get the first filename in fpath
Do While Len(fNAME) > 0
dim ext as string, p as integer
p = inStrRev(fName, ".")
ext = ucase(mid(fName, p+1))
if ext = "CSV" or ext = "XLS" or ext = "XLSX" or ext = "XLST" then
Set wb1 = Workbooks.Open(fPATH & fNAME) 'open the file
...
end if
You can get all Files in the Folder and check then if the file is an CSV or xlsx File. And then Open it like you did.
Option Explicit
Sub ImportGroups()
Dim fPATH As String, fNAME As String
Dim LR As Long, LastRow As Long
Dim wb2, wb1 As Workbook, ofs As Worksheet
Set ofs = ThisWorkbook.Sheets("Sheet3")
fPATH = "C:\Users\ashokkumar.d\Desktop\MFI\"
fNAME = Dir(fPATH & "*.*") 'get the first filename in fpath
Do While Len(fNAME) > 0
If Right(fNAME, 4) = "xlsx" Or Right(fNAME, 4) = ".csv" Then
Set wb1 = Workbooks.Open(fPATH & fNAME) 'open the file
LastRow = ofs.Range("B" & Rows.Count).End(xlUp).Row
ofs.Range("B" & LastRow).Offset(1, -1).Value = fNAME
Sheets("Input").Range("C8:J12").Copy
ofs.Range("B" & LastRow).Offset(1, 0).PasteSpecial xlPasteValues
wb1.Close False 'close data workbook
fNAME = Dir 'get the next filename
end if
Loop
LR = ofs.Range("C" & Rows.Count).End(xlUp).Row
ofs.Range("E2:I" & LR).Select
Selection.NumberFormat = "0.00%"
Application.ScreenUpdating = True
ofs.Range("A1:Z" & LR).Select
With Selection
WrapText = True
End With
End Sub
I tied Save As my sheet in CSV format with (Comma Delimited) "," for fields and {CR}{LF} for records in line by below code.
The issue is:
1) Generated file is delimited by ";" sign instead of ",".
2) Be sure records are separated by {CR}{LF}
3) How can define encoding as Unicode UTF-8 (in situation if needed)
I want this file have save by .txt extension.
How can I generate CSV file in true format by above situation?
Sub GenCSV()
Dim NewBook As Workbook
Set NewBook = Workbooks.Add
ThisWorkbook.Worksheets("Sheet1").Range("tblTaxRep[[Header1]: _
[Headern]]").SpecialCells(xlCellTypeVisible).Copy
With NewBook
.Worksheets("Sheet1").Cells(1, 1).PasteSpecial (xlPasteValues)
.SaveAs Filename:=ThisWorkbook.Path & "Report" & ".txt", FileFormat:=xlCSV
.Close SaveChanges:=False
End With
End Sub
Option Explicit
Const strDelimiter = """"
Const strDelimiterEscaped = strDelimiter & strDelimiter
Const strSeparator = ","
Const strRowEnd = vbCrLf
Const strCharset = "utf-8"
Function CsvFormatString(strRaw As String) As String
Dim boolNeedsDelimiting As Boolean
boolNeedsDelimiting = InStr(1, strRaw, strDelimiter) > 0 _
Or InStr(1, strRaw, Chr(10)) > 0 _
Or InStr(1, strRaw, strSeparator) > 0
CsvFormatString = strRaw
If boolNeedsDelimiting Then
CsvFormatString = strDelimiter & _
Replace(strRaw, strDelimiter, strDelimiterEscaped) & _
strDelimiter
End If
End Function
Function CsvFormatRow(rngRow As Range) As String
Dim arrCsvRow() As String
ReDim arrCsvRow(rngRow.Cells.Count - 1)
Dim rngCell As Range
Dim lngIndex As Long
lngIndex = 0
For Each rngCell In rngRow.Cells
arrCsvRow(lngIndex) = CsvFormatString(rngCell.Text)
lngIndex = lngIndex + 1
Next rngCell
CsvFormatRow = Join(arrCsvRow, ",") & strRowEnd
End Function
Sub CsvExportRange( _
rngRange As Range, _
Optional strFileName As Variant _
)
Dim rngRow As Range
Dim objStream As Object
If IsMissing(strFileName) Or IsEmpty(strFileName) Then
strFileName = Application.GetSaveAsFilename( _
InitialFileName:=ActiveWorkbook.Path & "\" & rngRange.Worksheet.Name & ".csv", _
FileFilter:="CSV (*.csv), *.csv", _
Title:="Export CSV")
End If
Set objStream = CreateObject("ADODB.Stream")
objStream.Type = 2
objStream.Charset = strCharset
objStream.Open
For Each rngRow In rngRange.Rows
objStream.WriteText CsvFormatRow(rngRow)
Next rngRow
objStream.SaveToFile strFileName, 2
objStream.Close
End Sub
Sub CsvExportSelection()
CsvExportRange ActiveWindow.Selection
End Sub
Sub CsvExportSheet(varSheetIndex As Variant)
Dim wksSheet As Worksheet
Set wksSheet = Sheets(varSheetIndex)
CsvExportRange wksSheet.UsedRange
End Sub
Reference
Thanks in advance for your help and comments.
I have the following problem, but I do not know if it is possible ... I am trying to rename PDF files that are in the folder C: \ ... I need to rename according to a worksheet that I have in excel that is ordered according to the pdf files .. I would like to rename with the spreadsheet data in excel?
I have a code that I researched but it does not search my database, but it asks me to enter the name of each file
Public Sub lsSelecionaArquivo()
Dim Caminho As String
Dim NomeBase As String
Caminho = InputBox("Informe o local dos arquivos a serem renomeados:", "Pasta", "C:\TEMP")
NomeBase = InputBox("Informe o local dos arquivos a serem renomeados:", "Renomear", "")
lsRenomearArquivos Caminho, NomeBase
End Sub
Public Sub lsRenomearArquivos(Caminho As String, NomeBase As String)
Dim FSO As Object, Pasta As Object, Arquivo As Object, Arquivos As Object
Dim Linha As Long
Dim lSeq As Long
Dim lNovoNome As String
Set FSO = CreateObject("Scripting.FileSystemObject")
If Not FSO.FolderExists(Caminho) Then
MsgBox "A pasta '" & Caminho & "' não existe.", vbCritical, "Erro"
Exit Sub
End If
lSeq = 1
Set Pasta = FSO.GetFolder(Caminho)
Set Arquivos = Pasta.Files
Cells(1, 1) = "De"
Cells(1, 2) = "Para"
Linha = 2
For Each Arquivo In Arquivos
Cells(Linha, 1) = UCase$(Arquivo.Path)
lNovoNome = Caminho & "\" & NomeBase & lSeq & Right(Arquivo, 4)
Name Arquivo.Path As lNovoNome
Cells(Linha, 2) = lNovoNome
lSeq = lSeq + 1
Linha = Linha + 1
Next
End Sub
For the renaming part, consider this.
Sub RenameFiles()
'Updateby20141124
Dim xDir As String
Dim xFile As String
Dim xRow As Long
With Application.FileDialog(msoFileDialogFolderPicker)
.AllowMultiSelect = False
If .Show = -1 Then
xDir = .SelectedItems(1)
xFile = Dir(xDir & Application.PathSeparator & "*")
Do Until xFile = ""
xRow = 0
On Error Resume Next
xRow = Application.Match(xFile, Range("A:A"), 0)
If xRow > 0 Then
Name xDir & Application.PathSeparator & xFile As _
xDir & Application.PathSeparator & Cells(xRow, "B").Value
End If
xFile = Dir
Loop
End If
End With
End Sub
https://www.extendoffice.com/documents/excel/2339-excel-rename-files-in-a-folder.html
Also, consider this.
Sub ListFiles()
Dim MyFolder As String
Dim MyFile As String
Dim j As Integer
MyFolder = "C:\DealerExam"
MyFile = Dir(MyFolder & "\*.*")
a = 0
Do While MyFile <> ""
a = a + 1
Cells(a, 1).Value = MyFile
MyFile = Dir
Loop
End Sub
This will list all the files in your directory starting in cell 'A1'
Thanks for the help
It is a bit tense to change language since I study Java and started doing VBA.
When I ran the code, I saw that it is necessary for the spreadsheet to have the old file name and the new one to insert the data, but there is no way to get it to just get the new data? And I've tried searching on how to make them as PDF without having to put the file extension in the worksheet.
Sorry for the questions ... I do not have much contact with VBA.
I thank you very much for helping me.
Sub RenameFiles()
Dim xDir As String
Dim xFile As String
Dim xRow As Long
With Application.FileDialog(msoFileDialogFolderPicker)
.AllowMultiSelect = False
If .Show = -1 Then
xDir = .SelectedItems(1)
xFile = Dir(xDir & Application.PathSeparator & "*")
Do Until xFile = ""
xRow = 0
On Error Resume Next
xRow = Application.Match(xFile, Range("A:A"), 0)
If xRow > 0 Then
Name xDir & Application.PathSeparator & xFile As _
xDir & Application.PathSeparator & Cells(xRow, "B").Value
End If
xFile = Dir
Loop
End If
End With
End Sub
Sub ListFiles()
Dim MyFolder As String
Dim MyFile As String
Dim j As Integer
MyFolder = "C:\Users\AnaWill\Desktop\Holerites Folha\Nova pasta"
MyFile = Dir(MyFolder & "\*.*")
a = 0
Do While MyFile <> ""
a = a + 1
Cells(a, 2).Value = MyFile
MyFile = Dir
Loop
End Sub
I am trying to upload a few hundred folders each with files inside of them into SharePoint, but unfortunately SharePoint doesn't allow any special characters like "%".
I'm trying to use a VBA code that can automatically go into each subfolder and replace any special characters contained within the files such as "%", "#", etc.
So far what I have is:
Sub ChangeFileName()
Set objFSO = CreateObject("Scripting.FileSystemObject")
Set Folder = objFSO.GetFolder("C:\Users\Documents\TEST\Subfolder")
'Currently the way I have it requires me to change my path a few hundred times
For Each File In Folder.Files
sNewFile = File.Name
sNewFile = Replace(sNewFile, "%", "_")
sNewFile = Replace(sNewFile, "#", "_")
'^and so on`
If (sNewFile <> File.Name) Then
File.Move (File.ParentFolder + "\" + sNewFile)
End If
Next
End Sub
However for the script above, you need the specific sub-folder path. Wondering if there's any way to automatically replace the special characters of files within subfolders. I can also paste all the specific subfolder paths into column A of my Excel worksheet if that helps.
Thank you!
I use this code
Sub GetFileFromFolder()
Dim fd As FileDialog
Dim strFolder As String
Dim colResult As Collection
Dim i As Long, k As Long
Dim vSplit
Dim strFn As String
Dim vR() As String
Dim p As String
Dim iLevel As Integer, cnt As Long
'iLevel = InputBox(" Subfolder step : ex) 2 ")
p = Application.PathSeparator
Set fd = Application.FileDialog(msoFileDialogFolderPicker)
With fd
.Show
.InitialView = msoFileDialogViewList
.Title = "Select your Root folder"
.AllowMultiSelect = False
If .SelectedItems.Count = 0 Then
Else
strFolder = .SelectedItems(1)
Set colResult = SearchFolder(strFolder)
i = colResult.Count
For k = 1 To i
vSplit = Split(colResult(k), p)
strFn = vSplit(UBound(vSplit))
strFn = Replace(strFn, "%", "_")
strFn = Replace(strFn, "#", "_")
'If UBound(vSplit) - UBound(Split(strFolder, p)) = iLevel Then
cnt = cnt + 1
ReDim Preserve vR(1 To 3, 1 To cnt)
On Error Resume Next
Err.Clear
Name colResult(k) As strFolder & strFn
vR(1, cnt) = colResult(k)
If Err.Number = 58 Then
strFn = Split(strFn, ".")(0) & "_" & vSplit(UBound(vSplit) - 1) & "_" & Date & "." & Split(strFn, ".")(1)
Name colResult(k) As strFolder & strFn
vR(2, cnt) = strFolder & strFn
vR(3, cnt) = "Changed name " 'When filename is duplicated chage filename
Else
vR(2, cnt) = strFolder & strFn
End If
' End If
Next k
ActiveSheet.UsedRange.Offset(1).Clear
Range("a3").Resize(1, 3) = Array("Old file", "New file", "Ect")
If cnt > 0 Then
Range("a4").Resize(cnt, 3) = WorksheetFunction.Transpose(vR)
End If
With ActiveSheet.UsedRange
.Borders.LineStyle = xlContinuous
.Columns.AutoFit
.Font.Size = 9
End With
End If
End With
MsgBox cnt & " files moved!! "
End Sub
Function SearchFolder(strRoot As String)
Dim FS As Object
Dim fsFD As Object
Dim f As Object
Dim colFile As Collection
Dim p As String
On Error Resume Next
p = Application.PathSeparator
If Right(strRoot, 1) = p Then
Else
strRoot = strRoot & p
End If
Set FS = CreateObject("Scripting.FileSystemObject")
Set fsFD = FS.GetFolder(strRoot)
Set colFile = New Collection
For Each f In fsFD.Files
colFile.Add f.Path
Next f
SearchSubfolder colFile, fsFD
Set SearchFolder = colFile
Set fsFD = Nothing
Set FS = Nothing
Set colFile = Nothing
End Function
Sub SearchSubfolder(colFile As Collection, objFolder As Object)
Dim sbFolder As Object
Dim f As Object
For Each sbFolder In objFolder.subfolders
SearchSubfolder colFile, sbFolder
For Each f In sbFolder.Files
colFile.Add f.Path
Next f
Next sbFolder
End Sub
i am using the following vba code to import all my text files onto a new row in excel. This bit works fine, the next thing I want to do is once this has imported the text files, I want each text file to be moved from one directory 'Z:\NS\Unactioned\' to another directory called Actioned 'Z:\NS\Actioned\&Filename\'.
And within that folder create a folder for each of the text files from the filename (minus the file extension) where i can then place each text file in the corresponding folder.
So if I had 3 .txt files in my folder Unactioned:
1.txt
2.txt
3.txt
then each txt file would be moved like so:
Actioned/1/1.txt
Actioned/2/2.txt
Actioned/3/3.txt
Can someone please show me how I would do this? Thanks
Code:
Sub Import_All_Text_Files_2007()
Dim nxt_row As Long
'Change Path
Const strPath As String = "Z:\NS\Unactioned\"
Dim strExtension As String
'Stop Screen Flickering
Application.ScreenUpdating = False
ChDir strPath
'Change extension
strExtension = Dir(strPath & "*.txt")
Do While strExtension <> ""
'Sets Row Number for Data to Begin
If Range("C1").Value = "" Then
nxt_row = 1
Else
If Range("C2").Value = "" Then
nxt_row = 2
Else
nxt_row = Range("C1").End(xlDown).Offset(1).Row
End If
End If
'Below is from a recorded macro importing a text file
FileNum = FreeFile()
curCol = 3
Open strPath & strExtension For Input As #FileNum
While Not EOF(FileNum)
Line Input #FileNum, DataLine
ActiveSheet.Cells(nxt_row, curCol) = DataLine
curCol = curCol + 1
Wend
Close #FileNum
strExtension = Dir
Loop
Dim d As String, ext, x
Dim srcPath As String, destPath As String, srcFile As String
srcPath = "Z:\NS\Unactioned\"
destPath = "Z:\NS\Actioned\" & srcFile & "\"
ext = Array("*.txt", "*.xls")
For Each x In ext
d = Dir(srcPath & x)
Do While d <> ""
srcFile = srcPath & d
FileCopy srcFile, destPath & d
Kill srcFile
d = Dir
Loop
Next
Application.ScreenUpdating = True
End Sub
You misplaced destPath so it wasn't filled with the document name.
Forgot to create destination directory (with MKDir) and the arguments of the last d=Dir statement
Try this (works for me) :
Sub Import_All_Text_Files_2007()
Dim d As String, ext, x
Dim srcPath As String, destPath As String, srcFile As String
Dim strExtension As String
Dim nxt_row As Long
'Change Path
Const strPath As String = "Z:\NS\Unactioned\"
'Stop Screen Flickering
Application.ScreenUpdating = False
ChDir strPath
'Change extension
strExtension = Dir(strPath & "*.txt")
Do While strExtension <> ""
'Sets Row Number for Data to Begin
If Range("C" & Rows.Count).End(xlUp).Offset(1).Row >= 5 Then
nxt_row = Range("C" & Rows.Count).End(xlUp).Offset(1).Row
Else
nxt_row = 5
End If
'Below is from a recorded macro importing a text file
FileNum = FreeFile()
curCol = 3
Open strPath & strExtension For Input As #FileNum
While Not EOF(FileNum)
Line Input #FileNum, DataLine
ActiveSheet.Cells(nxt_row, curCol) = DataLine
curCol = curCol + 1
Wend
Close #FileNum
strExtension = Dir
Loop
srcPath = "Z:\NS\Unactioned\"
ext = Array("*.txt", "*.xls")
For Each x In ext
d = Dir(srcPath & x)
Do While d <> ""
srcFile = srcPath & d
destPath = "Z:\NS\Actioned\" & Left(d, Len(d) - 4) & "\"
If Dir(destPath, 16) = "" Then MkDir (destPath)
FileCopy srcFile, destPath & d
Kill srcFile
d = Dir(srcPath & x)
Loop
Next x
Application.ScreenUpdating = True
End Sub