Reducing ActiveSheet Paste size. Large data showing insufficient memory - excel

Would like seek help on simplifying down some codes. it worked on some smaller set of data but unable to work on this larger set of around 750rows of data. The aim is to simplify down the data set by the criteria of Banker, and saved each filtered results based on Banker on a new tab, and then save as a separate workbook.
Sub seperate_by_banker()
Dim i, n As Integer
Dim banker As String
i = 2
n = Sheets("Banker").Range("A1").End(xlDown).Row
Do Until i = n
banker = Sheets("Banker").Range("A" & i)
Sheets("ASIA CHINA (PC)").Select
ActiveSheet.Range("$A$1:$Y$1000").AutoFilter Field:=7, Criteria1:= _
banker
Range("A1").Select
Range(Selection, Selection.End(xlDown)).Select
Range(Selection, Selection.End(xlToRight)).Select
Selection.Copy
Sheets.Add After:=ActiveSheet
ActiveSheet.Paste
ActiveSheet.Name = banker
i = i + 1
Loop
Call SplitWorkbook
End Sub
Sub SplitWorkbook()
'Updateby20200806
Dim FileExtStr As String
Dim FileFormatNum As Long
Dim xWs As Worksheet
Dim xWb As Workbook
Dim xNWb As Workbook
Dim FolderName As String
Application.ScreenUpdating = False
Set xWb = Application.ThisWorkbook
DateString = Format(Now, "yyyy-mm-dd hh-mm-ss")
FolderName = xWb.Path & "\" & xWb.Name & " " & DateString
If Val(Application.Version) < 12 Then
FileExtStr = ".xls": FileFormatNum = -4143
Else
Select Case xWb.FileFormat
Case 51:
FileExtStr = ".xlsx": FileFormatNum = 51
Case 52:
If Application.ActiveWorkbook.HasVBProject Then
FileExtStr = ".xlsm": FileFormatNum = 52
Else
FileExtStr = ".xlsx": FileFormatNum = 51
End If
Case 56:
FileExtStr = ".xls": FileFormatNum = 56
Case Else:
FileExtStr = ".xlsb": FileFormatNum = 50
End Select
End If
MkDir FolderName
For Each xWs In xWb.Worksheets
On Error GoTo NErro
If xWs.Visible = xlSheetVisible Then
xWs.Select
xWs.Copy
xFile = FolderName & "\" & xWs.Name & FileExtStr
Set xNWb = Application.Workbooks.Item(Application.Workbooks.Count)
xNWb.SaveAs xFile, FileFormat:=FileFormatNum
xNWb.Close False, xFile
End If
NErro:
xWb.Activate
Next
MsgBox "You can find the files in " & FolderName
Application.ScreenUpdating = True
End Sub

Please, try the next code. It uses array and copy the filtered range after transforming it in an array, so it should be very fast. No need of the second sub, no need of selections, which only consume Excel resources:
Sub seperate_by_banker()
Dim shB As Worksheet, shAC As Worksheet, wbNew As Workbook, lastR As Long, lastRAC As Long
Dim banker As String, rng As Range, rngF As Range, arrB, arr, i As Long, FolderName As String
Set shB = ThisWorkbook.Sheets("Banker")
lastR = shB.Range("A" & shB.rows.count).End(xlUp).row 'last row
arrB = shB.Range("A2:A" & lastR).Value2
Set shAC = ThisWorkbook.Sheets("ASIA CHINA (PC)")
lastRAC = shAC.Range("A" & shAC.rows.count).End(xlUp).row 'last row
FolderName = ThisWorkbook.path & "\" & ThisWorkbook.Name & " " & Format(Now, "yyyy-mm-dd hh-mm-ss")
If Dir(FolderName, vbDirectory) = "" Then MkDir FolderName 'create the folder if it does not exist
For i = 1 To UBound(arrB)
banker = arrB(i, 1)
shAC.AutoFilterMode = False 'eliminate the previous filter, if any
Set rng = shAC.Range("A1:Y" & lastRAC) 'set the range to be processed
rng.AutoFilter field:=6, Criteria1:=banker
Set rngF = rng.SpecialCells(xlCellTypeVisible) 'set a range to keep the filtered cells in the range
arr = arrayFromDiscRange(rngF, False) 'header inclusive
'create the necessary new workbook:
Set wbNew = Workbooks.Add
With wbNew.Sheets(1).Range("A1").Resize(UBound(arr), UBound(arr, 2))
.value = arr
.EntireColumn.AutoFit
End With
wbNew.saveas FolderName & "\" & banker & ".xlsx"
wbNew.Close False
Next i
End Sub
And the necessary function. It transforms the filtered (discontinuous) range in an array and paste it as fast as possible:
Private Function arrayFromDiscRange(rngF As Range, Optional NoHeader As Boolean = False) As Variant
Dim arr, i As Long, j As Long, k As Long, A As Range, R As Range, iRows As Long
'count range rows
For Each A In rngF.Areas
iRows = iRows + A.rows.count
Next A
'Redim the array to keep the range
ReDim arr(1 To iRows - IIf(NoHeader, 1, 0), 1 To rngF.Columns.count): k = 1
For Each A In rngF.Areas 'iterate between the range areas:
For Each R In A.rows 'iterate between the area rows:
If NoHeader And k = 1 Then GoTo Later 'skip the first row, if no header wanted
For j = 1 To R.Columns.count 'iterate between the area row columns:
arr(k, j) = R.cells(1, j).value 'place each row cells value in the array row
Next j
k = k + 1 'increment the array row to receive values
Later:
Next
Next A
arrayFromDiscRange = arr 'returning the created array
End Function

You could create the new workbooks directly from the filtered sheet.
Option Explicit
Sub separate_by_banker()
Dim wb As Workbook, wbNew As Workbook
Dim ws As Worksheet, wsData As Worksheet
Dim rng As Range, arBanker As Variant
Dim n As Long, iLastRow As Long
Dim foldername As String, sName As String
Set wb = ThisWorkbook
Set ws = wb.Sheets("Banker")
iLastRow = ws.Cells(Rows.Count, "A").End(xlUp).Row
arBanker = ws.Range("A2:A" & iLastRow).Value2
Set wsData = wb.Sheets("ASIA CHINA (PC)")
iLastRow = wsData.Cells(Rows.Count, "A").End(xlUp).Row
Set rng = wsData.Range("A1:Y" & iLastRow)
' make folder for workbooks
foldername = wb.Path & "\" & wb.Name & " " & Format(Now, "yyyy-mm-dd hh-mm-ss")
MkDir foldername
Application.ScreenUpdating = False
For n = 1 To UBound(arBanker)
sName = arBanker(n, 1)
Set wbNew = Workbooks.Add(xlWBATWorksheet) ' 1 sheet
wbNew.Sheets(1).Name = sName
rng.AutoFilter Field:=7, Criteria1:=sName
rng.Copy
wbNew.Sheets(1).Paste
wbNew.Sheets(1).Columns("A:Y").AutoFit
wbNew.SaveAs foldername & "\" & sName & ".xlsx"
wbNew.Close False
Next
wsData.AutoFilterMode = False
Application.CutCopyMode = False
Application.ScreenUpdating = True
MsgBox n-1 & " files created in " & foldername, vbInformation
End Sub

Related

How to find a value with the Find function?

How do I find a value with the Find function?
I want to copy specific data from an external Excel file to the current workbook.
I added Option Explicit to test for errors but it could just spot that I didn't declare the variable. The output is the same.
Sub ReadDataFromCloseFile()
'
' ReadDataFromCloseFile Macro
'
'
On Error GoTo ErrHandler
Application.ScreenUpdating = False
Dim wb As Workbook
Set wb = ThisWorkbook
Dim src As Workbook
' OPEN THE SOURCE EXCEL WORKBOOK IN "READ ONLY MODE".
Set src = Workbooks.Open("C:\test.xlsm", True, True)
Dim masterRow_count As Integer
masterRow_count = wb.Worksheets("Sheet1").Range("A1").End(xlDown).Row
Dim row_number As Integer
row_number = 2
Dim strSearch As String
Dim searchrange As Range
Do
Dim result As Range
strSearch = wb.Worksheets("Sheet1").Range("A" & row_number).Value
Set searchrange = src.Worksheets("Sheet1").Range("D:D")
Set result = searchrange.Find(what:=strSearch, LookIn:=xlValues, lookat:=xlValues)
If Not result Is Nothing Then
'Get the data from Asiamiles
src.Worksheets("Sheet1").Range("AB" & result.Row).Copy wb.Worksheets("Sheet1").Range("B", row_number)
src.Worksheets("Sheet1").Range("J" & result.Row).Copy wb.Worksheets("Sheet1").Range("C", row_number)
src.Worksheets("Sheet1").Range("I" & result.Row).Copy wb.Worksheets("Sheet1").Range("D", row_number)
src.Worksheets("Sheet1").Range("N" & result.Row).Copy wb.Worksheets("Sheet1").Range("E", row_number)
src.Worksheets("Sheet1").Range("AD" & result.Row).Copy wb.Worksheets("Sheet1").Range("F", row_number)
src.Worksheets("Sheet1").Range("P" & result.Row).Copy wb.Worksheets("Sheet1").Range("G", row_number)
src.Worksheets("Sheet1").Range("Q" & result.Row).Copy wb.Worksheets("Sheet1").Range("H", row_number)
End If
row_number = row_number + 1
Loop Until row_number = masterRow_count
src.Close SaveChanges:=False
Set src = Nothing
ErrHandler:
Application.EnableEvents = True
Application.ScreenUpdating = True
End Sub
There is another problem .It could not close the Excel workbook. But that is not the largest issue.
LookAt:=xlValues should be LookAt:=xlPart or LookAt:=xlWhole, Range("B", row_number) should be Range("B" & row_number)
Option Explicit
Sub ReadDataFromCloseFile()
Const SRC_WB = "C:\test.xlsm"
Dim wb As Workbook, wbSrc As Workbook
Dim ws As Worksheet, wsSrc As Worksheet
Dim masterRow_count As Long, row_number As Long
Dim rngSearch As Range, rngResult As Range, strSearch As String
Dim i As Long, n As Long, ar, t0 As Single
t0 = Timer
' OPEN THE SOURCE EXCEL WORKBOOK IN "READ ONLY MODE".
Application.ScreenUpdating = False
Set wbSrc = Workbooks.Open(SRC_WB, True, True)
Set wsSrc = wbSrc.Worksheets("Sheet1")
With wsSrc
i = .Cells(.Rows.Count, "D").End(xlUp).Row
Set rngSearch = wsSrc.Range("D1:D" & i)
End With
Set wb = ThisWorkbook
Set ws = wb.Worksheets("Sheet1")
ar = Split("AB,J,I,N,AD,P,Q", ",")
With ws
masterRow_count = .Range("A" & .Rows.Count).End(xlUp).Row
For row_number = 2 To masterRow_count
strSearch = .Range("A" & row_number).Value
Set rngResult = rngSearch.Find(what:=strSearch, _
LookIn:=xlValues, lookat:=xlWhole)
If Not rngResult Is Nothing Then
'Get the data from Asiamiles
For i = 0 To UBound(ar)
.Cells(row_number, "B").Offset(0, i) = wsSrc.Cells(rngResult.Row, ar(i))
Next
n = n + 1
End If
Next
End With
wbSrc.Close SaveChanges:=False
Application.ScreenUpdating = True
MsgBox row_number - 1 & " rows scanned, " & _
n & " rows updated", vbInformation, Format(Timer - t0, "0.0 secs")
End Sub

Deleting duplicate values

I'm trying to delete all duplicate rows based on Column B and leave only the unique rows.
It will leave one of the duplicate entries. I tried with > 1 and = 2.
Sub test1()
Dim fName As String, fPath As String, wb As Workbook, sh As Worksheet, i As Long, lCopyLastRow As Long, lDestLastRow As Long
Set sh = ActiveSheet
fPath = ThisWorkbook.Path & "\"
fName = Dir(fPath & "*.xls*")
Do
If fName <> ThisWorkbook.Name Then
Set wb = Workbooks.Open(fPath & fName)
lCopyLastRow = wb.Sheets(1).Cells(wb.Sheets(1).Rows.Count, "A").End(xlUp).Row
lDestLastRow = sh.Cells(sh.Rows.Count, "A").End(xlUp).Offset(1).Row
wb.Sheets(1).Range("A2:AA1000" & lCopyLastRow).Copy sh.Range("B" & lDestLastRow)
sh.Range("A1") = "Source"
With sh
.Range(.Cells(Rows.Count, 1).End(xlUp)(2), .Cells(Rows.Count, 2).End(xlUp).Offset(, -1)) = fName
End With
wb.Close
End If
Set wb = Nothing
fName = Dir
Loop Until fName = ""
For i = sh.UsedRange.Rows.Count To 2 Step -1
If Application.CountIf(sh.Range("B:B"), sh.Cells(i, 2).Value) > 1 Then Rows(i).Delete
Next
End Sub
The problem with your code is, that you countIf on the remaining rows - if you already deleted the "other" duplicates the first one is a unique value in the then remaining list.
So you have to count the occurences before deleting.
Sub removeNonUniqueRows()
Dim arrCountOccurences As Variant
ReDim arrCountOccurences(2 To sh.UsedRange.Rows.Count)
Dim i As Long
For i = 2 To sh.UsedRange.Rows.Count
arrCountOccurences(i) = Application.CountIf(sh.Range("B:B"), sh.Cells(i, 2).Value)
Next
For i = sh.UsedRange.Rows.Count To 2 Step -1
If arrCountOccurences(i) > 1 Then sh.Rows(i).Delete
Next
End Sub

Excel VBA filter multiple sheets on name and save as a seperate file

I have a report with 4 worksheets: 1 frontpage and 3 worksheets that have to be filtered on a name. Once filtered, the sheets have to be saved as a seperate file.
I am using the following code now (see below), but I have some questions:
How do I remove the data that does not meet the criteria? So when the data is filtered on Name1, all other Names should be removed.
How do I copy the frontpage (sheet1) together with the 3 filtered sheets into 1 file? It now only copies the 3 filtered sheets. The frontpage does not need to be filtered.
How do I paste the data as values (it's pasted as formula now)?
Option Explicit
Sub AutoFilters()
Dim sheetsToFilter As Variant, sheetName As Variant
Dim sheetsColumnToFilterOn As Variant
Dim criteria As Variant, criterium As Variant
Dim iSht As Long
Dim pre As String
sheetsToFilter = Array("Sheet2", "Sheet3", "Sheet4")
sheetsColumnToFilterOn = Array(2, 3, 4)
criteria = Array("Name1", "Name2", "Name3")
pre = Format(Now, "dd-mm-yyyy")
Application.ScreenUpdating = False
For Each criterium In criteria
For iSht = LBound(sheetsToFilter) To UBound(sheetsToFilter)
Call Autofilter(ThisWorkbook.Worksheets(sheetsToFilter(iSht)).Range("A1"), CLng(sheetsColumnToFilterOn(iSht)), CStr(criterium))
Next iSht
Call CopySheet(sheetsToFilter, ThisWorkbook.Path & "\" & criterium & " " & pre & ".xlsx")
Next criterium
Application.ScreenUpdating = True
End Sub
Sub Autofilter(rng As Range, col As Long, criteria As String)
With rng
.Autofilter
.Autofilter field:=col, Criteria1:=criteria & "*", VisibleDropDown:=True
End With
End Sub
Sub CopySheet(sheetsToFilter As Variant, shtName As String)
ThisWorkbook.Worksheets(sheetsToFilter).Copy
ActiveWorkbook.SaveAs Filename:=shtName, FileFormat:=xlWorkbookDefault
ActiveWorkbook.Close False
End Sub
Thanks in advance!
Backup Worksheets
"<>" & Criteria(n) & "*"
swb.Worksheets(Array(wsNames(0), wsNames(n))).Copy
rg.Value = rg.Value
Option Explicit
Sub CreateBackups()
Const wsNamesList As String = "Sheet1,Sheet2,Sheet3,Sheet4"
Const CriteriaList As String = ",Name1,Name2,Name3"
Dim fFields As Variant: fFields = VBA.Array(, 2, 3, 4)
Dim wsNames() As String: wsNames = Split(wsNamesList, ",")
Dim Criteria() As String: Criteria = Split(CriteriaList, ",")
Dim dStamp As String: dStamp = Format(Date, "dd-mm-yyyy")
Dim swb As Workbook: Set swb = ThisWorkbook ' workbook containing this code
Dim dFolderPath As String: dFolderPath = swb.Path
Application.ScreenUpdating = False
Dim dwb As Workbook
Dim ws As Worksheet
Dim rg As Range
Dim drg As Range ' Delete Range
Dim dFilePath As String
Dim n As Long
For n = 1 To UBound(wsNames) ' 0 is front sheet
swb.Worksheets(Array(wsNames(0), wsNames(n))).Copy
Set dwb = ActiveWorkbook
Set ws = dwb.Worksheets(wsNames(n))
If ws.AutoFilterMode Then ws.AutoFilterMode = False
Set rg = ws.Range("A1").CurrentRegion
rg.Value = rg.Value
rg.AutoFilter fFields(n), "<>" & Criteria(n) & "*"
Set drg = Nothing
On Error Resume Next
rg.Resize(rg.Rows.Count - 1, 1).Offset(1, fFields(n) - 1) _
.SpecialCells(xlCellTypeVisible).EntireRow.Delete
On Error GoTo 0
ws.AutoFilterMode = False
dFilePath = dFolderPath & "\" & Criteria(n) & " " & dStamp & ".xlsx"
Application.DisplayAlerts = False ' overwrite without alerts
dwb.SaveAs dFilePath, xlWorkbookDefault
Application.DisplayAlerts = True
dwb.Close
Next n
Application.ScreenUpdating = False
MsgBox "Today's worksheet backups created.", vbInformation, "Backup"
End Sub

Convert Multiple Excel Sheet Ranges as PDF VBA

The below code is take the Status of Col"E" If it is = Include then its corresponding sheets ranges will will be converted to PDF.
I have tried at my end but its not working receiving an error invalid procedure call or argument on the line
rng.ExportAsFixedFormat Type:=xlTypePDF, _
Filename:=saveLocation
Your help will be appreciated to fix the problem.
Sub SelectSheets_Ranges()
Dim sh As Worksheet, lastR As Long, rng As Range, arr, arrSplit, i As Long, k As Long
Set sh = ActiveSheet
lastR = sh.Range("C" & sh.Rows.Count).End(xlUp).Row
ReDim arr(lastR - 1)
For i = 6 To lastR
If sh.Range("E" & i).Value = "Include" Then
arr(k) = sh.Range("C" & i).Value & "|" & sh.Range("D" & i).Value: k = k + 1
End If
Next i
ReDim Preserve arr(k - 1)
For i = 0 To UBound(arr)
arrSplit = Split(arr(i), "|")
Set rng = Worksheets(arrSplit(0)).Range(arrSplit(1))
'Create and assign variables
Dim saveLocation As String
saveLocation = "C:\Users\marks\OneDrive\Documents\myPDFFile.pdf"
'Save a range as PDF
rng.ExportAsFixedFormat Type:=xlTypePDF, _
Filename:=saveLocation
Next
End Sub
Please, try the next code. It saves in ThisWorkbook path, naming the pdf file as "myPDFFile_sheetName.pdf". Each created file will be open in the default pdf application. If it works OK, you can appropriately change the last parameter:
Sub SelectSheets_Ranges_ExpPdf()
Dim sh As Worksheet, lastR As Long, rng As Range, arr, arrSplit, i As Long, k As Long
Set sh = ActiveSheet
lastR = sh.Range("C" & sh.Rows.Count).End(xlUp).Row
ReDim arr(lastR - 1)
For i = 6 To lastR
If sh.Range("E" & i).Value = "Include" Then
arr(k) = sh.Range("C" & i).Value & "|" & sh.Range("D" & i).Value: k = k + 1
End If
Next i
If k > 0 Then
ReDim Preserve arr(k - 1)
Else
MsgBox "No appropriate range (containing ""Include"") could be found...:exit sub"
End If
Dim boolHide As Boolean, boolProt As Boolean
ActiveWorkbook.Unprotect "4321" 'in order to unprotect he workbook structure
For i = 0 To UBound(arr)
boolHide = False: boolProt = False
arrSplit = Split(arr(i), "|")
Set rng = Worksheets(arrSplit(0)).Range(arrSplit(1))
If ActiveWorkbook.Sheets(arrSplit(0)).ProtectContents Then _
ActiveWorkbook.Sheets(arrSplit(0)).Unprotect "4321": boolProt = True
Debug.Print arrSplit(0)
If ActiveWorkbook.Sheets(arrSplit(0)).Visible <> xlSheetVisible Then _
ActiveWorkbook.Sheets(arrSplit(0)).Visible = xlSheetVisible: boolHide = True
'Create and assign variables
Dim saveLocation As String
saveLocation = ThisWorkbook.Path & "\myPDFFile_" & arrSplit(0) & ".pdf"
'Save a range as PDF
rng.ExportAsFixedFormat Type:=xlTypePDF, Filename:= _
saveLocation, Quality:=xlQualityStandard, IgnorePrintAreas:=False, OpenAfterPublish:=True
If boolHide Then ActiveWorkbook.Sheets(arrSplit(0)).Visible = xlSheetHidden
If boolProt Then ActiveWorkbook.Sheets(arrSplit(0)).Protect "4321"
Next
ActiveWorkbook.Protect "4321"
End Sub
Try this:
Sub SelectSheets_Ranges()
Dim sh As Worksheet, i As Long
Dim saveLocation As String, FirstSheet As Boolean
saveLocation = "C:\Users\marks\OneDrive\Documents\myPDFFile.pdf"
Set sh = ActiveSheet
FirstSheet = True
For i = 6 To sh.Range("C" & sh.Rows.Count).End(xlUp).Row
If sh.Cells(i, "E") = "Include" Then
'FirstSheet determines whether the sheet is added to currently-selected
' sheets or not (if not then it replaces them)
ThisWorkbook.Sheets(sh.Cells(i, "C").Value).Select FirstSheet
FirstSheet = False
End If
Next i
If Not FirstSheet Then
'at least one sheet was included
ActiveSheet.ExportAsFixedFormat Type:=xlTypePDF, Filename:=saveLocation
End If
End Sub
I assume you want all the ranges from the different sheets in one pdf.
Option Explicit
Sub SelectSheets_Ranges()
Const FOLDER = "C:\Users\marks\OneDrive\Documents\"
Const FILENAME = "myPDFFile.pdf"
Dim wb As Workbook, wbPDF As Workbook
Dim sh As Worksheet, wsPDF As Worksheet
Dim lastR As Long, rng As Range, r As Long, n As Integer, m As Integer
Set sh = ActiveSheet
Set wb = ActiveWorkbook
lastR = sh.Range("C" & sh.Rows.Count).End(xlUp).Row
' create temp workbook to hold ranges
Set wbPDF = Workbooks.Add
m = wbPDF.Sheets.Count
n = m
With sh
For r = 6 To lastR
If .Cells(r, "E").Value = "Include" Then
Set rng = wb.Sheets(.Cells(r, "C").Value).Range(.Cells(r, "D").Value)
Set wsPDF = wbPDF.Sheets.Add(After:=wbPDF.Sheets(n))
rng.Copy wsPDF.Range("A1")
n = n + 1
End If
Next
End With
' delete initial sheets
Application.DisplayAlerts = False
For n = m To 1 Step -1
wbPDF.Sheets(n).Delete
Next
Application.DisplayAlerts = True
'end
wbPDF.ExportAsFixedFormat Type:=xlTypePDF, FILENAME:=FOLDER & FILENAME
'wbPDF.SaveAs FOLDER & "debug.xlsx"
wbPDF.Close False
MsgBox "PDF created " & FOLDER & FILENAME, vbInformation
End Sub

Excel Macro Multiple Sheets to CSV

I have a macro that I am running in Excel to separate 49 sheets into individual CSV files.
However, it is getting caught up on line 7
Application.ActiveWorkbook.SaveAs Filename: = xcsvFile, _
FileFormat: = xlCSV, CreateBackup: = False
Here's the surrounding code:
Sub ExportSheetsToCSV()
Dim xWs As Worksheet
For Each xWs In Application.ActiveWorkbook.Worksheets
xWs.Copy
Dim xcsvFile As String
xcsvFile = CurDir & "\" & xWs.Name & ".csv"
Application.ActiveWorkbook.SaveAs Filename: = xcsvFile, _
FileFormat: = xlCSV, CreateBackup: = False
Application.ActiveWorkbook.Saved = True
Application.ActiveWorkbook.Close
Next
End Sub
For each Sheet in workbook, transfer each sheet's name csv file.
Sub ExportSheetsToCSV()
Dim Ws As Worksheet
Dim xcsvFile As String
Dim rngDB As Range
For Each Ws In Worksheets
xcsvFile = CurDir & "\" & Ws.Name & ".csv"
With Ws
r = .Cells.Find("*", SearchOrder:=xlByRows, SearchDirection:=xlPrevious).Row
c = .Cells.Find("*", SearchOrder:=xlByColumns, SearchDirection:=xlPrevious).Column
Set rngDB = .Range("a1", .Cells(r, c))
End With
TransToCSV xcsvFile, rngDB
Next
MsgBox ("Files Saved Successfully")
End Sub
Sub TransToCSV(myfile As String, rng As Range)
Dim vDB, vR() As String, vTxt()
Dim i As Long, n As Long, j As Integer
Dim objStream
Dim strTxt As String
Set objStream = CreateObject("ADODB.Stream")
vDB = rng
For i = 1 To UBound(vDB, 1)
n = n + 1
ReDim vR(1 To UBound(vDB, 2))
For j = 1 To UBound(vDB, 2)
vR(j) = vDB(i, j)
Next j
ReDim Preserve vTxt(1 To n)
vTxt(n) = Join(vR, ",")
Next i
strTxt = Join(vTxt, vbCrLf)
With objStream
'.Charset = "utf-8"
.Open
.WriteText strTxt
.SaveToFile myfile, 2
.Close
End With
Set objStream = Nothing
End Sub
Consider this.
Sub test()
Dim ws As Worksheet
Dim GetSheetName As String
For Each ws In ThisWorkbook.Worksheets
If ws.Name <> "Sheet1" Then ' Assuming there is one sheet that you DON'T want to save as a CSV
ws.Select
GetSheetName = ActiveSheet.Name
Set shtToExport = ActiveSheet ' Sheet to export as CSV
Set wbkExport = Application.Workbooks.Add
shtToExport.Copy Before:=wbkExport.Worksheets(wbkExport.Worksheets.Count)
Application.DisplayAlerts = False ' Possibly overwrite without asking
wbkExport.SaveAs Filename:="C:\your_path_here\Desktop\" & GetSheetName & ".csv", FileFormat:=xlCSV
Application.DisplayAlerts = True
wbkExport.Close SaveChanges:=False
End If
Next ws
End Sub

Resources