Find and replace char in multiple csv files - vba

I have several csv files in one folder. I want to add these files into one excel files with multiple worksheets.
Before I add them in my excel sheet I want to replace . with ,, because of my convention in excel.
However, the code below gives me:
Here is my code:
Option Explicit
Sub ImportCSVs()
'Summary: Import all CSV files from a folder into separate sheets
' named for the CSV filenames
Dim fPath As String
Dim fCSV As String
Dim fnd As Variant
Dim rplc As Variant
Dim wbCSV As Workbook
'add your find and replace values!
'#############################
fnd = "."
rplc = ","
Application.ScreenUpdating = False 'speed up macro
'path to CSV files, include the final \
'#############################
fPath = "C:\Users\Desktop\Data\23-3-2015_Data\"
fCSV = Dir(fPath & "*.csv") 'start the CSV file listing
Do While Len(fCSV) > 0
Set wbCSV = Workbooks.Open(fPath & fCSV) 'open a CSV file and move
'find and replace the . by ,
For Each wbCSV In ActiveWorkbook.Worksheets
wbCSV.Cells.Replace what:=fnd, Replacement:=rplc, _
LookAt:=xlPart, SearchOrder:=xlByRows, MatchCase:=False, _
SearchFormat:=False, ReplaceFormat:=False
Next wbCSV
ActiveSheet.Move After:=ThisWorkbook.Sheets(Sheets.Count)
fCSV = Dir 'ready next CSV
Loop
Application.ScreenUpdating = True
Set wbCSV = Nothing
End Sub
Any recommendation what I am doing wrong?
I appreciate your reply!

Try this:
'add to your Dim statements:
Dim ws as Worksheet
'change your Do loop to:
Do While Len(fCSV) > 0
Set wbCSV = Workbooks.Open(fPath & fCSV) 'open a CSV file and move
'find and replace the . by ,
For Each ws In wbcsv
ws.Cells.Replace what:=fnd, Replacement:=rplc, _
LookAt:=xlPart, SearchOrder:=xlByRows, MatchCase:=False, _
SearchFormat:=False, ReplaceFormat:=False
Next ws
Also, I find it's easier to debug things if you leave the Application.ScreenUpdating = False commented out until everything's working. You're not all that worried about execution speed when you're debugging.
An alternative loop since you're opening a CSV, there can only be one worksheet in it, this should simplify things a bit:
Dim DestBook as workbook
Set DestBook = ThisWorkbook
'other setup stuff...
Do While Len(fCSV) > 0
Set wbCSV = Workbooks.Open(fPath & fCSV) 'open a CSV file and move
'find and replace the . by ,
wbCSV.worksheet(1).Cells.Replace what:=fnd, Replacement:=rplc, _
LookAt:=xlPart, SearchOrder:=xlByRows, MatchCase:=False, _
SearchFormat:=False, ReplaceFormat:=False
wbcsv.move after:=DestBook.sheets(DestBook.sheets.count)
wbCSV.close
vFCSV = Dir
Loop
I also noted that the move was moving it to ThisWorkbook and there's no guarantee what that would be when you got there. So, I declared a new WorkBook variable and assigned it to ThisWorkbook before doing anything, that way you're 100% certain where you're moving it to. I also closed the CSV that we opened, just for some tidying up.

In the error line For Each wbCSV In ActiveWorkbook.Worksheets you want to loop through all the worksheets but you are using wbCSV which is declared As Workbook.
To solve the type mismatch add a new variable Dim wsCSV As Worksheet and use this new variable in the loop as a reference for each worksheet.
The loop could look like this :
For Each wsCSV In wbCSV.Worksheets
wsCSV.Cells.Replace what:=fnd, Replacement:=rplc, _
LookAt:=xlPart, SearchOrder:=xlByRows, MatchCase:=False, _
SearchFormat:=False, ReplaceFormat:=False
Next wsCSV

wbCSV is workbook object not worksheet .
try this
Dim ws as Worksheet
for each ws in activeworkbook.worksheets

I don't know your method for going through wbCSV, never did it but doesn't seem right...
I cant suggest you use what I posted here just by switching "xml" to "csv" :
https://stackoverflow.com/questions/29184595/loop-on-all-files-in-the-same-directory-then-detect-extension-type/29187762#29187762
I think it'll be a rather good start for what you have to do! ;)

Related

Converting workbook in PDF without blank pages

Hiii
I wrote a code to export sheets from one workbook to an other workbook and then convert it in pdf, but I have a lot of blank pages (maybe because of hidden formula or I don't know.
If you have any idea for what to add to my code in order to have a decent file it would be very appreciated.
Workbooks.Open FileName:="C:\Users\User\Documents\Tests Salome\dailypdf.xlsx"
Dim wbto2 As Workbook: Set wbto2 = Workbooks("dailypdf.xlsx")
wb.Activate
For Each sht In Sheets
If sht.Name <> "USD" And sht.Name <> "Balance" Then
Else
sht.Copy Before:=wbto2.Sheets(wbto2.Sheets.Count)
Rows("140:351").EntireRow.Delete '(I tried to delete the hidden rows)
End If
Debug.Print sht.Name
Next
wbto2.Activate
Application.DisplayAlerts = False
Sheets("Sheet1").Delete
Application.DisplayAlerts = True
FileName = Create_PDF(Source:=wbto2, _
FixedFilePathName:=iFile, _
OverwriteIfFileExist:=True, _
OpenPDFAfterPublish:=False)
The code functions but the result does not satisfy me because of the blank pages..
you can try any option below
1.Delete all unwanted rows before saving as PDF.
2.Set Print area
3.try to save excel range as PDF directly
'Enter Worksheet name, range Address, PDF file path and name
Sheets("Sheet Name").Range("A1:D50").ExportAsFixedFormat Type:=xlTypePDF, Filename:= _
"C:\Temp\PDF_name.pdf", Quality:= _
xlQualityStandard, IncludeDocProperties:=True, IgnorePrintAreas:=False, _
OpenAfterPublish:=True

Macro to revert changes since save

I found an old script online to close the document without saving the changes, then re-open the document:
Sub RevertFile()
wkname = ActiveWorkbook.Path & "\" & ActiveWorkbook.Name
ActiveWorkbook.Close Savechanges:=False
Workbooks.Open Filename:=wkname
End Sub
I want this since you can't "undo" changes caused by running a macro. However, it does not seem to work in MS Office v1609. Firstly, the document does not re-open after it is closed. Secondly, the modifications are saved when I want them not to be. How can I rewrite this script to get it to work? Thanks.
[edit]
Here is the other sub-routine I am using.
Sub FixPlatforms()
'PURPOSE: Find & Replace a list of text/values throughout entire workbook
'SOURCE: www.TheSpreadsheetGuru.com/the-code-vault
Dim sht As Worksheet
Dim platList As Variant
Dim x As Long
platList = Array _
( _
"PS4", "PlayStation 4", _
"PS3", "PlayStation 3", _
"PS2", "PlayStation 2", _
"PSV", "PlayStation Vita", _
"PSP", "PlayStation Portable", _
"WIN", "Microsoft Windows", _
"SNES", "Super Nintendo Entertainment System" _
)
'Loop through each item in Array lists
For x = 1 To UBound(platList) Step 2
'Loop through each worksheet in ActiveWorkbook
For Each sht In ActiveWorkbook.Worksheets
sht.Cells.Replace What:=platList(x), Replacement:=platList(x - 1), _
LookAt:=xlPart, SearchOrder:=xlByRows, MatchCase:=False, _
SearchFormat:=False, ReplaceFormat:=False
Next sht
Next x
End Sub
Is there something wrong with it?
You shouldn't have to close the workbook in any event. Attempting to open a workbook that is already open produces the following.
Adding application.displayalerts = false should be sufficient to avoid that confirmation.
Option Explicit
Sub RevertFile()
Dim wkname As String
wkname = ActiveWorkbook.Path & "\" & ActiveWorkbook.Name
Application.DisplayAlerts = False
Workbooks.Open Filename:=wkname
Application.DisplayAlerts = True
End Sub

Rebuild a workbook with VBA

I am trying to run the below VBA that I found online. The purpose of the code is to copy the data from all of the worksheets in a workbook to a different workbook. A couple key points:
1) I am trying to copy the data in all worksheets NOT the actual worksheets to the new workbook
2) The macro does a lot: makes sure you have a back-up file; creates a new worksheet (TargetWorkbook) and saves with the source workbook's name; etc. however, the most important part (and where I believe it is erroring) is copying the worksheets
3) I understand what is going on with the code but not savvy enough to make it work.
Sub Update_SmartView_Workbook()
' Copies sheets from a source workbook to new and current Excel target workbook to
' get rid of the "2003 or earlier backbone" that interferes with SmartView.
' Keyboard Shortcut: Ctrl+z
' Copyleft 2013 By MJ Henderson. No rights reserved. Free and worth every penny.
' User assumes all risk. No warranties implied or otherwise.
Dim ConfirmBackup As Integer
Dim SourceWorkbook, TargetWorkbook As Workbook
Dim SourceWorksheet As Worksheet
Dim SourceWorkbookName As String
' User must make a backup before proceeding.
ConfirmBackup = MsgBox("Have you made a backup copy of the source file?", vbYesNo, "Confirm Backup")
If ConfirmBackup = vbNo Then
MsgBox "Try again when you have a backup copy of the source file", vbOKOnly, "Backup Required"
Exit Sub
End If
' Find and open the source file
Application.FindFile
Set SourceWorkbook = ActiveWorkbook
SourceWorkbookName = ActiveWorkbook.Name
SourceWorkbookDirectoryPath = Left(ActiveWorkbook.FullName, Len(ActiveWorkbook.FullName) - Len(SourceWorkbookName))
' Create a new target workbook in the same folder as the source workbook
Workbooks.Add
ActiveWorkbook.SaveAs _
Filename:=SourceWorkbookDirectoryPath & "TargetWorkbook.xlsx", _
FileFormat:=xlOpenXMLWorkbook, ConflictResolution:=True
' Copy each worksheet in SourceWorkbook to TargetWorkbook THIS IS WHERE THE FIX IS NEEDED
SourceWorkbook.Activate
For Each SourceWorksheet In SourceWorkbook.Worksheets
SourceWorksheet.Cells.Copy
Windows("TargetWorkbook.xlsx").Activate
ActiveWindow.WindowState = xlNormal
On Error Resume Next
TargetWorkbook.Sheets(SourceWorksheet.Name).Delete
Range("A1").Select
ActiveSheet.Paste
Range("A1").Select
ActiveSheet.Name = SourceWorksheet.Name
Application.CutCopyMode = cancel
Next
' Close SourceWorkbook, rename SourceWorkbook with suffix "_OLD"
SourceWorkbook.Activate
SourceWorkbook.Saved = True
SourceWorkbook.Close SaveChanges:=False
Name SourceWorkbookDirectoryPath & SourceWorkbookName As SourceWorkbookDirectoryPath & SourceWorkbookName & "_OLD"
' Global replace to remove any references to old workbook. (Fixes interbook links.)
Cells.Replace What:="[" & SourceWorkbookName & "]", _
Replacement:="", LookAt:=xlPart, SearchOrder:=xlByRows, MatchCase:= _
False, SearchFormat:=False, ReplaceFormat:=False
' Rename TargetWorkbook as SourceWorkbook's original name, delete TargetWorkbook
TargetWorkbook.Activate
ActiveWorkbook.SaveAs _
Filename:=SourceWorkbookDirectoryPath & SourceWorkbookName, _
FileFormat:=xlOpenXMLWorkbook
ActiveWorkbook.Saved = True
ActiveWorkbook.Close SaveChanges:=False
Kill SourceWorkbookDirectoryPath & "TargetWorkbook.xlsx"
End Sub
I believe these lines are driving the error:
Windows("TargetWorkbook.xlsx").Activate
ActiveWindow.WindowState = xlNormal
The error I am getting is "Run Time Error 9 - Subscript out of Range"
Any idea on how to fix?
Use Workbooks("TargetWorkbook.xlsx").Activate instead of Windows...
I would recommend to eliminate the activating if the sheet and workbooks; we do not need it. Just referencing the object is enough.
This is an untested code see how it goes you might need to change it a little bit to fit your needs.
Option Explicit
Sub Test()
Dim ConfirmBackup As Integer
Dim SourceWorkbook, TargetWorkbook As Workbook
Dim SourceWorksheet As Worksheet
Dim SourceWorkbookName As String
Dim SourceWorkbookDirectoryPath As String
' User must make a backup before proceeding.
ConfirmBackup = MsgBox("Have you made a backup copy of the source file?", vbYesNo, "Confirm Backup")
If ConfirmBackup = vbNo Then
MsgBox "Try again when you have a backup copy of the source file", vbOKOnly, "Backup Required"
Exit Sub
End If
' Find and open the source file
Application.FindFile
Set SourceWorkbook = ActiveWorkbook
SourceWorkbookName = ActiveWorkbook.Name
SourceWorkbookDirectoryPath = Left(ActiveWorkbook.FullName, Len(ActiveWorkbook.FullName) - Len(SourceWorkbookName))
' Create a new target workbook in the same folder as the source workbook
Workbooks.Add
ActiveWorkbook.SaveAs _
Filename:=SourceWorkbookDirectoryPath & "TargetWorkbook.xlsx", _
FileFormat:=xlOpenXMLWorkbook, ConflictResolution:=True
' Copy each worksheet in SourceWorkbook to TargetWorkbook THIS IS WHERE THE FIX IS NEEDED
For Each SourceWorksheet In SourceWorkbook.Worksheets
TargetWorkbook.Sheets(SourceWorksheet.Name).Delete
SourceWorksheet.Copy After:=TargetWorkbook.Sheets(TargetWorkbook.Sheets.Count)
Next
' Close SourceWorkbook, rename SourceWorkbook with suffix "_OLD"
SourceWorkbook.Close SaveChanges:=True
Name SourceWorkbookDirectoryPath & SourceWorkbookName As SourceWorkbookDirectoryPath & SourceWorkbookName & "_OLD"
' Global replace to remove any references to old workbook. (Fixes interbook links.)
Cells.Replace What:="[" & SourceWorkbookName & "]", _
Replacement:="", LookAt:=xlPart, SearchOrder:=xlByRows, MatchCase:= _
False, SearchFormat:=False, ReplaceFormat:=False
' Rename TargetWorkbook as SourceWorkbook's original name, delete TargetWorkbook
ActiveWorkbook.SaveAs _
Filename:=SourceWorkbookDirectoryPath & SourceWorkbookName, _
FileFormat:=xlOpenXMLWorkbook
ActiveWorkbook.Close SaveChanges:=True
Kill SourceWorkbookDirectoryPath & "TargetWorkbook.xlsx"
End Sub
I hope it helps

Excel VBA find string : Error 2015

I have to following code snippet ...
Public Sub FindText(path As String, file As String)
Dim Found As Range
myText = "test("
MacroBook = ActiveWorkbook.Name
' Open the File
Workbooks.Open path & file, ReadOnly:=True, UpdateLinks:=False
For Each ws In Workbooks(file).Worksheets
With ws
Set Found = .UsedRange.Find(What:=myText, LookIn:=xlFormulas, _
LookAt:=xlPart, MatchCase:=False)
If Not Found Is Nothing Then
' do stuff
' ...
I see in the debugger that Found contains Error 2015! The sheet contains the text I want in the formula.
Any ideas why I'm getting the error?
Thanks
As follow up from comments to the Q, Error 2015 occurs because your formula in the sheet returns #VALUE! error. You can handle it using IsError:
If Not Found Is Nothing Then
If Not IsError(Found) Then
' do sth
End If
End If
You don't need to use 'Set' in your code. You only use this to assign a reference to an object. Try:-
For Each ws In Workbooks(file).Worksheets
With ws
Found = .UsedRange.Find(What:=myText, LookIn:=xlFormulas, _
LookAt:=xlPart, MatchCase:=False)
If Not Found Is Nothing Then
' do stuff
' ...
Hopefully this should work.

VBA Excel - find a value in a column, paste to another sheet

I've got a folder of excel worksheets, and also another worksheet with a column whose entries correspond to the file names of the worksheets in the folder.
The column to the right of the worksheet names has a number, which I want to paste into each corresponding worksheet... but it's not working... here's my code so far :
Sub FraisRank()
Dim folderPath As String
Dim filename As String
Dim filenameshort As String
Dim wb As Workbook
Dim fraislist As Workbook
Dim find As Range
Dim sel As Range
folderPath = "C:\Users\richard\Desktop\temp"
If Right(folderPath, 1) <> "\" Then folderPath = folderPath + "\"
Set fraislist = Workbooks.Open("C:\Users\richard\desktop\frais list.xlsx")
filename = Dir(folderPath & "*.*")
Do While filename <> ""
Application.ScreenUpdating = False
Set wb = Workbooks.Open(folderPath & filename)
filenameshort = Left(filename, Len(filename) - 4)
Set sel = fraislist.Sheets(1).Range("A1:A164")
Set find = sel.find(What:=filenameshort, After:=ActiveCell, LookIn:=xlFormulas, _
LookAt:=xlWhole, SearchOrder:=xlByRows, SearchDirection:=xlNext, _
MatchCase:=False, SearchFormat:=False)
If find Is Nothing Then
MsgBox ("Cell " & filenameshort & " not found")
Else
find.Offset(, 1).Resize(1, 1).Copy
ActiveSheet.Range("$H$5").PasteSpecial Paste:=xlPasteValues
End If
ActiveWorkbook.Save
ActiveWorkbook.Close
filename = Dir
Loop
End Sub
For the moment I'm getting a Runtime error '13', type mismatch on the 'Set find = ...' part. And in general I don't really understand how to run the '.find' on the selected cells in the 'fraislist' workbook...
The problem with ActiveCell is that it will always refer to the Activesheet and hence statements like Activecell/Select/Activate/ActiveSheet/Activeworkbook should be avoided. Always create relevant objects and work with them
INTERESTING READ
In your case it is not necessary that the ActiveSheet is fraislist.Sheets(1) so ActiveCell might not be referring to the correct sheet and hence, it's better to qualify it completely.
If you change After:=ActiveCell to After:=fraislist.Sheets(1).Range("A1") then your code will refer to the correct sheet and it will work.