I have a csv file which I want to transform. The problem is that the columns contain integers lower than 5000. In the columns are also identifiers, e.g. IE0034230957 and BLANK values. They should not change when applying the code.
The csv should open and produce a new file.
Could someone help me with a change in the code that works?
I read topics about this and could come to this code, however it doesn't work:
Sub RemoveSmallValues()
Dim myfilename As String
Dim myfilepath As String
Dim newfilename As String
Dim N As Long
Dim i As Long
Dim cellvalue As Long
Dim rng As Range, r As Range, lm As Double
Application.ScreenUpdating = False
Application.Calculation = xlCalculationManual
myfilepath = "Q:\Pre trade"
myfilename = "Snapshot_of_Model.csv"
Workbooks.Open (myfilepath)
Workbooks(myfilename).Activate 'Makes SnapShot.csv the active workbook
Set rng = Range("D:F")
lm = 5000
For Each r In rng
If r.Value < lm Then
r.Clear
Next r
newfilename = "Q:\Snapshot_final.csv" 'new file path and file name without extension.
Workbooks(myfilename).SaveAs newfilename, FileFormat:=xlCSV 'Save the file with extension CSV
ActiveWorkbook.Close False 'Close the workbook without saving, as you have already saved the workbook with line before.
End Sub
Off your question, I would code similarly like so
Sub t()
Dim r As Excel.Range
Dim c As Excel.Range
Set r = Range("a1").Resize(Cells(Rows.Count, 1).End(xlUp).Row, 1)
For Each c In r.Cells
If IsNumeric(c.Value) Then
If CDbl(c.Value) < 5000 Then c.Clear
End If
Next c
Set r = Nothing
End Sub
It can also be done using SQL and ADO.
Sub x()
Dim cnCSVConnection As ADODB.Connection
Dim rstResults As ADODB.Recordset
Set cnCSVConnection = New ADODB.Connection
cnCSVConnection.ConnectionString = "Provider=Microsoft.Jet.OLEDB.4.0;" & _
"Data Source=C:\Workspace\SW Pensions\RUFUS\;" & _
"Extended Properties=""text;HDR=Yes;FMT=Delimited"";"
'"C:\Workspace\"
cnCSVConnection.Open
Set rstResults = New ADODB.Recordset
rstResults.Open "Select [Entry-date],[Current value of policy]," & _
"iif([Current value of policy]<100,1,0) from " & _
"[Bonds Claims_WIP_TESTING.csv]", cnCSVConnection, adOpenKeyset
Range("a1").CopyFromRecordset rstResults
rstResults.Close
cnCSVConnection.Close
Set rstResults = Nothing
Set cnCSVConnection = Nothing
End Sub
Related
I'm working on a database that will compile 4 recordsets together in order to output 3 excel worksheets into a single workbook for each workcenter or Office Symbol. This will be updated weekly and new workbooks produced at each update.
I've managed to stumble my way into creating the workbooks the way I want them. However, saving the files has become an issue. The beginning of this sub creates a folder using today's date. Everything following creates the individual reports. The issue comes when I attempt to use the "wb.Saveas". Instead of saving the reports with the name from the "Do While Not" in the created folder, it saves it using today's date and the "Do While Not" output (See attached images).
I also have an issue with the Select Queries (AD1, PT1 and LV1) not giving me consistent results. Instead of filtering to only 1 Office Symbol, some of the time I get 3 or 4 on one excel output.
Thanks in advance for help with this.
Please excuse my lack of consistency with coding. I'm stumbling my way through this and I don't know the proper formatting etiquette.
incorrect naming format
Private Sub Export_Button_Click()
Dim sFolderName As String, sFolder As String
Dim sFolderPath As String
sFolder = "C:\Users\1023491733A\Desktop\TEST\"
sFolderName = Format(Now, "dd MMM yyyy")
sFolderPath = "C:\Users\1023491733A\Desktop\TEST\" & sFolderName
Set oFSO = CreateObject("Scripting.FileSystemObject")
If oFSO.FolderExists(sFolderPath) Then
MsgBox "Folder already exists with today's date!", vbInformation, "VBAF1"
Else
MkDir sFolderPath
MsgBox "Folder has created with today's date: " & vbCrLf & vbCrLf & sFolderPath, vbInformation, "VBAF1"
End If
Dim db As DAO.Database
Set db = CurrentDb
Dim OS As DAO.Recordset
Set OS = db.OpenRecordset("Office_Symbols")
Dim AD As DAO.Recordset
Set AD = db.OpenRecordset("XLS-Airfield")
Dim PT As DAO.Recordset
Set PT = db.OpenRecordset("XLS-Fitness")
Dim LV As DAO.Recordset
Set LV = db.OpenRecordset("XLS-Leave")
Dim xl
Set xl = CreateObject("Excel.Application")
Dim wb As Object
Set wb = xl.Workbooks.Add("C:\Users\1023491733A\Desktop\TEST\Template.xlsx")
Dim wr As Object
Set wr = wb.Worksheets("Airfield")
Dim ws As Object
Set ws = wb.Worksheets("Fitness")
Dim wt As Object
Set wt = wb.Worksheets("Leave")
Do While Not OS.EOF
Dim AD1 As DAO.Recordset
Set AD1 = db.OpenRecordset("SELECT [XLS-Airfield].* FROM [XLS-Airfield] WHERE ([XLS-Airfield].OFFICE_SYMBOL)='" & OS.Fields(0) & "';")
Dim PT1 As DAO.Recordset
Set PT1 = db.OpenRecordset("SELECT [XLS-Fitness].* FROM [XLS-Fitness] WHERE ([XLS-Fitness].OFFICE_SYMBOL) ='" & OS.Fields(0) & "';")
Dim LV1 As DAO.Recordset
Set LV1 = db.OpenRecordset("SELECT [XLS-Leave].* FROM [XLS-Leave] WHERE ([XLS-Leave].OFFICE_SYMBOL) ='" & OS.Fields(0) & "';")
wr.Select
wr.Range("A1").Select
For Each fld In AD1.Fields
xl.ActiveCell = fld.Name
xl.ActiveCell.Offset(0, 1).Select
Next
AD1.MoveFirst
wr.Cells(2, 1).CopyFromRecordset AD1
'Break
ws.Activate
ws.Range("A1").Select
For Each fld In PT1.Fields
xl.ActiveCell = fld.Name
xl.ActiveCell.Offset(0, 1).Select
Next
PT1.MoveFirst
ws.Cells(2, 1).CopyFromRecordset PT1
'Break
wt.Activate
wt.Range("A1").Select
For Each fld In LV1.Fields
xl.ActiveCell = fld.Name
xl.ActiveCell.Offset(0, 1).Select
Next
LV1.MoveFirst
wt.Cells(2, 1).CopyFromRecordset LV1
Dim sFileName As String
sFileName = OS.Fields(0)
wb.SaveAs sFolderPath & sFileName
Set AD1 = Nothing
Set PT1 = Nothing
Set LV1 = Nothing
OS.MoveNext
Loop
OS.Close
wr.Rows("1:1").Font.Bold = True 'Row 1 Bold
wr.Cells.EntireColumn.AutoFit 'Autofit all the columns
ws.Rows("1:1").Font.Bold = True 'Row 1 Bold
ws.Cells.EntireColumn.AutoFit 'Autofit all the columns
wt.Rows("1:1").Font.Bold = True 'Row 1 Bold
wt.Cells.EntireColumn.AutoFit 'Autofit all the columns
Set OS = Nothing
Set AD = Nothing
Set PT = Nothing
Set LV = Nothing
End Sub
I have solved my issue. I'm not sure if it's the best solution but here are the changes I made.
Dim the objects was moved into the the Do While Not loop and each was set to nothing before the OS.MoveNext.
Do While Not OS.EOF
Dim xl As Object
Set xl = CreateObject("Excel.Application")
Dim wb As Object
Set wb = xl.Workbooks.Open("C:\Users\1023491733A\Desktop\TEST\Template.xlsx")
Dim wr As Object
Set wr = wb.Worksheets("Airfield")
Dim ws As Object
Set ws = wb.Worksheets("Fitness")
Dim wt As Object
Set wt = wb.Worksheets("Leave")
I added a backslash to sFolderName as below which helped. And for some reason unknown to me, using two variables ("sfolderpath" and "OS.Fields(0)) would always give a run-time 1004 error. But inserting a constant between them seems to fix this issue but again I'm not sure why.
sFolderName = (Format(Now, "dd MMM yyyy") & "\")
Dim sfilename As String
sfilename = sFolderPath & "TEST" & OS.Fields(0)
wb.SaveAs sfilename
I understand the first fix since the loop was using the excel workbook from the previous iteration. But I can't wrap my head around why the sFileName fix worked. If anyone can explain this I would greatly appreciate it.
I am using Office 365 on a Windows 10 64-bit pc.
I have a Word document with a table into which I want to copy elements from an Excel document. The elements are a) text from its cell, b) a hyperlink from its cell and c) images from a list of images.
The first two tasks are performed successfully by the following sub:
Sub ImportFromExcel()
Dim RowNo As Long, RowTarget As Long
Dim RowFirst As Long, RowLast As Long
Dim strContent As String, strLink As String, strDisplay As String
Dim xlAppl As New Excel.Application
Dim xlBook As New Excel.Workbook
Dim xlSheet As New Excel.Worksheet
Dim ExcelFileName As String
Dim tbl As Word.Table
On Error GoTo Finish
ExcelFileName = "C:\MyPath\MyExcelDoc.xlsm"
Set xlAppl = CreateObject("Excel.Application")
xlAppl.Application.Visible = False
xlAppl.Workbooks.Open ExcelFileName
Set xlBook = xlAppl.ActiveWorkbook
Set xlSheet = xlBook.Worksheets("Titan")
Set tbl = ActiveDocument.Tables(1)
RowFirst = 6: RowLast = 19
For RowNo = RowFirst To RowLast
RowTarget = RowNo - RowFirst + 1
strContent = xlSheet.Cells(RowNo, 5).Value
tbl.Cell(RowTarget, 1).Range.Text = strContent
strDisplay = xlSheet.Cells(RowNo, 3).Value
tbl.Cell(RowTarget, 3).Range.Text = strContent
strLink = xlSheet.Cells(RowNo, 3).Hyperlinks(1).Address
InsertHyperlinkInTable tbl, RowTarget, 3, strLink, strDisplay
' CopyImageFromExcelToWord xlSheet, RowTarget, tbl
Next RowNo
Finish:
xlAppl.ActiveWorkbook.Close False ' Word will not freeze at this point
xlAppl.Quit
Set xlSheet = Nothing
Set xlBook = Nothing
Set xlAppl = Nothing
End Sub
I copy the hyperlink by reading its address and caption and then recreating it in Word.
Also from Word I can select a give image by way of its index using the first two active lines of the following sub:
Sub CopyImageFromExcelToWord(xlSheet As Excel.Worksheet, imgNo As Long, tbl As Word.Table)
Dim strId As String
' Syntax at https://learn.microsoft.com/en-us/office/vba/api/excel.worksheet.select
strId = "Picture " & CStr(2 * imgNo)
xlSheet.Shapes.Range(Array(strId)).Select
' Missing link !
With tbl.Cell(1, 4)
.Range.ParagraphFormat.Alignment = wdAlignParagraphCenter
.VerticalAlignment = wdCellAlignVerticalCenter
.Select
End With
Selection.PasteAndFormat (wdFormatOriginalFormatting)
End Sub
An image residing in the clipboard can be inserted into Word using the last six lines.
But I have not found out how to copy the image I selected in the Excel document to the clipboard with a Word macro.
Can this be done somehow?
Can the copying of the hyperlink be performed in a smarter way?
Try
Sub CopyImageFromExcelToWord(xlSheet As Excel.Worksheet, imgNo As Long, tbl As Word.Table)
Dim strId As String
' Syntax at https://learn.microsoft.com/en-us/office/vba/api/excel.worksheet.select
strId = "Picture " & CStr(2 * imgNo)
xlSheet.Shapes.Range(Array(strId)).Item(1).Copy
With tbl.Cell(1, 4)
.Range.ParagraphFormat.Alignment = wdAlignParagraphCenter
.VerticalAlignment = wdCellAlignVerticalCenter
.Range.PasteAndFormat wdFormatOriginalFormatting
End With
End Sub
I have a working VBA Macro but for the life of me I can't get it to completely work as expected. The macro saves row data to individual .svg files. Up to this point everything is fine. The problem is that I encountered an issue where the macro added double quotes to the .svg files thus ruining them. This was as a result of xlCSV but I changed this to xlTextPrinter. This worked but once again I encountered an issue where the svg code breaks where it's not supposed to. For example
<ima
ge style="overflow:visible;"style="overflow:visible;" width="1200" height="682" ...
which ruins the code when you preview it.
I am completely stuck at this point. I want the macro to print just what is in the rows and that's it without interfering.
The macro is this one:
Sub SaveRowsAsSVGs()
Dim wb As Excel.Workbook, wbNew As Excel.Workbook
Dim wsSource As Excel.Worksheet, wsTemp As Excel.Worksheet
Dim r As Long, c As Long
Set wsSource = ThisWorkbook.Worksheets("Images")
Application.DisplayAlerts = False 'will overwrite existing files without asking
Application.ScreenUpdating = False
r = 1
Do Until Len(Trim(wsSource.Cells(r, 1).Value)) = 0
ThisWorkbook.Worksheets.Add ThisWorkbook.Worksheets(1)
Set wsTemp = ThisWorkbook.Worksheets(1)
For c = 2 To 7
wsTemp.Cells((c - 1) * 2 - 1, 1).Value = wsSource.Cells(r, c).Value
Next c
wsTemp.Move
Set wbNew = ActiveWorkbook
Set wsTemp = wbNew.Worksheets(1)
Dim myPath As String
myPath = "C:\Users\myname\Desktop\MJOMBA\Images\"
wbNew.SaveAs myPath & wsSource.Cells(r, 1).Value & ".svg", xlTextPrinter
'wbNew.SaveAs "cell.Text" & r & ".svg", xlCSV 'new way
wbNew.Close
ThisWorkbook.Activate
r = r + 1
Loop
Application.DisplayAlerts = False
End Sub
This code solved my problem perfectly.
Sub Export_SVG_Files()
Dim sExportFolder, sFN
Dim rArticleName As Range
Dim rDisclaimer As Range
Dim oSh As Worksheet
Dim oFS As Object
Dim oTxt As Object
'sExportFolder = path to the folder you want to export to
'oSh = The sheet where your data is stored
sExportFolder = "C:\Users\myname\Desktop\NewFolder\Images"
Set oSh = ThisWorkbook.Worksheets("Images")
Set oFS = CreateObject("Scripting.Filesystemobject")
For Each rArticleName In oSh.UsedRange.Columns("A").Cells
Set rDisclaimer = rArticleName.Offset(, 1)
'Add .txt to the article name as a file name
sFN = rArticleName.Value & ".svg"
Set oTxt = oFS.OpenTextFile(sExportFolder & "\" & sFN, 2, True)
oTxt.Write rDisclaimer.Value
oTxt.Close
Next
End Sub
I have about 100 Word documents and from each I want to copy data and paste it all in one Excel workbook.
I came up with this code which opens one Word document, copies data, pastes it to Excel and closes the Word document:
Sub WordDataToExcel()
Dim myObj
Dim myWB
Dim mySh
Dim txt As String, Lgth As Long, Strt As Long
Dim i As Long
Dim oRng As Range
Dim Tgt As String
Dim TgtFile As String
Dim arr()
Dim ArrSize As Long
Dim ArrIncrement As Long
ArrIncrement = 1000
ArrSize = ArrIncrement
ReDim arr(ArrSize)
Dim wrdDoc As Object
Documents.Open ("D:\ekr5_i.doc")
TgtFile = "result.xlsx"
Tgt = "D:\" & TgtFile
'finds the text string of Lgth lenght
txt = "thetext"
Lgth = 85
Strt = Len(txt)
'Return data to array
With Selection
.HomeKey unit:=wdStory
With .Find
.ClearFormatting
.Forward = True
.Text = txt
.Execute
While .Found
i = i + 1
Set oRng = ActiveDocument.Range _
(Start:=Selection.Range.Start + Strt, _
End:=Selection.Range.End + Lgth)
arr(i) = oRng.Text
oRng.Start = oRng.End
.Execute
If i = ArrSize - 20 Then
ArrSize = ArrSize + ArrIncrement
ReDim Preserve arr(ArrSize)
End If
Wend
End With
End With
ReDim Preserve arr(i)
'Set target and write data
Set myObj = CreateObject("Excel.Application")
Set myWB = myObj.Workbooks.Open(Tgt)
Set mySh = myWB.Sheets(1)
With mySh
.Range(.Cells(1, 1), .Cells(i, 1)) = myObj.Transpose(arr)
End With
'Tidy up
myWB.Close True
myObj.Quit
ActiveDocument.Close SaveChanges:=wdDoNotSaveChanges
Set mySh = Nothing
Set myWB = Nothing
Set myObj = Nothing
End Sub
I need to loop through all the documents in the folder.
I have implemented the same with Excel workbooks, but I don't know how for Word documents.
Here is the code for Excel workbooks:
Sub combine_into_one()
Dim FSO As Object: Set FSO = CreateObject("Scripting.FileSystemObject")
Dim strPath$, Pivot$, sUserName$, sFolderName$, sSourceName$, x&
Dim oFldialog As FileDialog
Dim oFolder
Application.DisplayAlerts = False
Application.ScreenUpdating = False
Set oFldialog = Application.FileDialog(msoFileDialogFolderPicker)
With oFldialog
If .Show = -1 Then
.Title = "Select a Folder"
.AllowMultiSelect = False
.InitialFileName = strPath
sFolderName = .SelectedItems(1)
End If
End With
Set oFolder = FSO.GetFolder(sFolderName)
Workbooks.Add: Pivot = ActiveWorkbook.Name 'Destination workbook
For Each oFile In oFolder.Files
Workbooks(Pivot).Activate
x = Workbooks(Pivot).Sheets(1).Cells.SpecialCells(xlCellTypeLastCell).Row + 1
Workbooks.Open Filename:=oFile: sSourceName = ActiveWorkbook.Name
Workbooks(sSourceName).Activate
Workbooks(sSourceName).Sheets(1).[A80:Q94].copy
Workbooks(Pivot).Activate
Workbooks(Pivot).Sheets(1).Cells(x + 1, 1).PasteSpecial xlPasteAll
Workbooks(sSourceName).Close False
Next
Application.CutCopyMode = False
Application.DisplayAlerts = True
Application.ScreenUpdating = True
End Sub
There are so, so, so many things you can do between Excel & Word. I'm not sure I totally understand your question. The script below may help you; it has definitely served me well over time. If you need something different, please describe your issue more, to better clarify the issue you are facing.
Sub OpenAndReadWordDoc()
Rows("2:1000000").Select
Range(Selection, Selection.End(xlDown)).Select
Selection.ClearContents
Range("A1").Select
' assumes that the previous procedure has been executed
Dim oWordApp As Word.Application
Dim oWordDoc As Word.Document
Dim blnStart As Boolean
Dim r As Long
Dim sFolder As String
Dim strFilePattern As String
Dim strFileName As String
Dim sFileName As String
Dim ws As Worksheet
Dim c As Long
Dim n As Long
'~~> Establish an Word application object
On Error Resume Next
Set oWordApp = GetObject(, "Word.Application")
If Err Then
Set oWordApp = CreateObject("Word.Application")
' We started Word for this macro
blnStart = True
End If
On Error GoTo ErrHandler
Set ws = ActiveSheet
r = 1 ' startrow for the copied text from the Word document
' Last column
n = ws.Range("A1").End(xlToRight).Column
sFolder = "C:\Users\Excel\Desktop\Coding\Microsoft Excel\PWC\Resumes\"
'~~> This is the extension you want to go in for
strFilePattern = "*.doc*"
'~~> Loop through the folder to get the word files
strFileName = Dir(sFolder & strFilePattern)
Do Until strFileName = ""
sFileName = sFolder & strFileName
'~~> Open the word doc
Set oWordDoc = oWordApp.Documents.Open(sFileName)
' Increase row number
r = r + 1
' Enter file name in column A
ws.Cells(r, 1).Value = sFileName
ActiveCell.Offset(1, 0).Select
ActiveSheet.Hyperlinks.Add Anchor:=Sheets("Sheet1").Range("A" & r), Address:=sFileName, _
SubAddress:="A" & r, TextToDisplay:=sFileName
' Loop through the columns
For c = 2 To n
If oWordDoc.Content.Find.Execute(FindText:=Trim(ws.Cells(1, c).Value), _
MatchWholeWord:=True, MatchCase:=False) Then
' If text found, enter Yes in column number c
ws.Cells(r, c).Value = "Yes"
End If
Next c
oWordDoc.Close SaveChanges:=False
'~~> Find next file
strFileName = Dir
Loop
ExitHandler:
On Error Resume Next
' close the Word application
Set oWordDoc = Nothing
If blnStart Then
' We started Word, so we close it
oWordApp.Quit
End If
Set oWordApp = Nothing
Exit Sub
ErrHandler:
MsgBox Err.Description, vbExclamation
Resume ExitHandler
End Sub
Function GetDirectory(path)
GetDirectory = Left(path, InStrRev(path, "\"))
End Function
In this scenario, whatever you put in the headers of B1:K1 (or more to the right) is searched for, each word document in a folder is opened, scanned, and if the string in B1:K1 is found, an 'x' is placed in the same x-y coordinate.
Again, if this doesn't help, please describe your issue better, and I'll post back with alternative solutions. Thanks!!
I'm not experienced with VBA, but I think it's the only way for this to work.
I need to send a report to each sales team, but don't want to send them the information of other sales team. There are multiple sheets per workbook with different reports which all have a sales team column.
I would like all the sheets to be filtered by sales team, and create a new workbook for each team.
I appreciate any help.
I got this solution.
Just send me an email if you need this solution.
At first I got this format:
I create the following macro code
Option Explicit
Dim MainWorkBook As Workbook
Dim NewWorkBook As Workbook
Sub ExportWorksheet()
Dim Pointer As Long
Set MainWorkBook = ActiveWorkbook
Range("E2").Value = MainWorkBook.Sheets.Count
Application.ScreenUpdating = False 'enhance the performance
For Pointer = 2 To MainWorkBook.Sheets.Count
Set NewWorkBook = Workbooks.Add
MainWorkBook.Sheets(Pointer).Copy After:=NewWorkBook.Sheets(1)
Application.DisplayAlerts = False
NewWorkBook.Sheets(1).Delete
Application.DisplayAlerts = True
With NewWorkBook
.SaveAs Filename:="C:\Users\lengkgan\Desktop\Testing\" & MainWorkBook.Sheets(Pointer).Name & ".xls" 'you may change to yours
End With
NewWorkBook.Close SaveChanges:=True
Next Pointer
Application.ScreenUpdating = True
Range("D5").Value = "Export Completed"
End Sub
Following is the output
I have written a VBA(Macro) program which will work based on Input data. All you need to do is, provide input data in a column in another sheet. Macro will read the data and filter Master Sheet based on each row then it Generate new excel sheet based on find data.
enter Option Explicit
Dim personRows As Range 'Stores all of the rows found
'Split data into separate columns baed on the names defined in
'a RepList on the 'Names' sheet.
Sub SplitSalesData()
Dim wb As Workbook
Dim p As Range
Dim counter2 As Integer
Dim i As Integer
counter2 = 0
i = 0
Application.ScreenUpdating = False
' in my case i am generating new excel based on every 8 reacords from begining. You can simplyfy this logic based on your need.
For Each p In Sheets("Names").Range("RepList") ' Give the name of your input sheet and column
If i = 0 Then ' We are starting, so generate new excel in memeory.
Workbooks.Add
Set wb = ActiveWorkbook
ThisWorkbook.Activate
End If
WritePersonToWorkbook wb, p.Value
i = i + 1 ' Increment the counter reach time
If i = 8 Then ' As my need is after processing every 8 uniqe record just save the excel sheet and reset the processing
counter2 = counter2 + 1
wb.SaveAs ThisWorkbook.Path & "\salesdata_" & CStr(counter2) ' save the data at current directory location.
wb.Close
Set personRows = Nothing ' Once the process has completed for curent excelsheet, set the personRows as NULL
i = 0
End If
Next p
Application.ScreenUpdating = True
Set wb = Nothing
End Sub
'Writes all the data rows belonging to a RepList
Sub WritePersonToWorkbook(ByVal SalesWB As Workbook, _
ByVal Person As String)
Dim rw As Range
Dim firstRW As Range
For Each rw In UsedRange.Rows
If Not Not firstRW Is Nothing And Not IsNull(rw) Then
Set firstRW = rw ' WE want to add first row in each excel sheet.
End If
If Person = rw.Cells(1, 5) Then ' My filter is working based on "FeederID"
If personRows Is Nothing Then
Set personRows = firstRW
Set personRows = Union(personRows, rw)
Else
Set personRows = Union(personRows, rw)
End If
End If
Next rw
personRows.Copy SalesWB.Sheets(1).Cells(1, 1) ' Adding data in Excel sheet.
End Sub
please find below code
Sub SplitSheetDataIntoMultipleWorkbooksBasedOnSpecificColumn()
Dim objWorksheet As Excel.Worksheet
Dim nLastRow, nRow, nNextRow As Integer
Dim strColumnValue As String
Dim objDictionary As Object
Dim varColumnValues As Variant
Dim varColumnValue As Variant
Dim objExcelWorkbook As Excel.Workbook
Dim objSheet As Excel.Worksheet
Dim icol As Long
Dim l As Long
Dim headercol As Long
Dim stroutputfolder As String
stroutputfolder = "D:\Ba"
'dim str
icol = 1
headercol = 3
Set objWorksheet = ActiveSheet
nLastRow = objWorksheet.Range("A" & objWorksheet.Rows.Count).End(xlUp).Row
Set objDictionary = CreateObject("Scripting.Dictionary")
For nRow = headercol + 1 To nLastRow
'Get the specific Column
'Here my instance is "B" column
'You can change it to your case
strColumnValue = objWorksheet.Cells(nRow, icol).Value
If objDictionary.Exists(strColumnValue) = False Then
objDictionary.Add strColumnValue, 1
End If
Next
varColumnValues = objDictionary.Keys
For i = LBound(varColumnValues) To UBound(varColumnValues)
varColumnValue = varColumnValues(i)
'MsgBox (varColumnValues(i))
If Dir(stroutputfolder, vbDirectory) = vbNullString Then MkDir stroutputfolder
If CStr(varColumnValue) <> "" Then
objWorksheet.UsedRange.Offset(headercol - 1, 0).AutoFilter Field:=icol, Criteria1:=CStr(varColumnValue)
Set objExcelWorkbook = Excel.Application.Workbooks.Add
Set objSheet = objExcelWorkbook.Sheets(1)
objSheet.Name = objWorksheet.Name
objWorksheet.UsedRange.SpecialCells(xlCellTypeVisible).Copy Destination:=[A1]
'strFilename = strOutputFolder & "\" & strItem
ActiveWorkbook.SaveAs Filename:=stroutputfolder & "\" & CStr(varColumnValue) & ".xlsb", FileFormat:=50
ActiveWorkbook.Close savechanges:=False
l = l + 1
End If
Next
objWorksheet.ShowAllData
MsgBox (l & " files splitted")
End Sub