-1

I have an excel file with complete mixture of data (column 1, Name). I want to split the data into multiple sheets in the same workbook based on the first column i.e., Name. I found solution to this in VBA but I want this is VB Script. Please help. Thanks in advance.

`Sub parse_data()
Dim lr As Long
Dim ws As Worksheet
Dim vcol, i As Integer
Dim icol As Long
Dim myarr As Variant
Dim title As String
Dim titlerow As Integer
vcol = 1
Set ws = Sheets("ZPC_STATS")
lr = ws.Cells(ws.Rows.Count, vcol).End(xlUp).Row
title = "A1:G1"
titlerow = ws.Range(title).Cells(1).Row
icol = ws.Columns.Count
ws.Cells(1, icol) = "Unique"
For i = 2 To lr
On Error Resume Next
If ws.Cells(i, vcol) <> "" And Application.WorksheetFunction.Match(ws.Cells(i, vcol), ws.Columns(icol), 0) = 0 Then
ws.Cells(ws.Rows.Count, icol).End(xlUp).Offset(1) = ws.Cells(i, vcol)
End If
Next
myarr = Application.WorksheetFunction.Transpose(ws.Columns(icol).SpecialCells(xlCellTypeConstants))
ws.Columns(icol).Clear
For i = 2 To UBound(myarr)
ws.Range(title).AutoFilter field:=vcol, Criteria1:=myarr(i) & ""
If Not Evaluate("=ISREF('" & myarr(i) & "'!A1)") Then
Sheets.Add(after:=Worksheets(Worksheets.Count)).Name = myarr(i) & ""
Else
Sheets(myarr(i) & "").Move after:=Worksheets(Worksheets.Count)
End If
ws.Range("A" & titlerow & ":A" & lr).EntireRow.Copy Sheets(myarr(i) & "").Range("A1")
Sheets(myarr(i) & "").Columns.AutoFit
Next
ws.AutoFilterMode = False
ws.Activate
End Sub`
Naveen
  • 3
  • 1
  • 3
  • What have you tried so far? Where are you stuck? Most things are pretty straight forward: Remove types in variable definition, use late binding. – FunThomas Jun 18 '18 at 07:51
  • @FunThomas I have added my VBA code. It works perfectly. I want it in VBScript and I also want to run the VBS when the excel is closed. – Naveen Jun 18 '18 at 08:05
  • Why split in multiple worksheets to begin with, very hard to report on later on. A simple table like you already have is a much better starting point. Have you considered creating a pivot table based on the table and using the name column as a slicer filter? – jkpieterse Jun 18 '18 at 08:06
  • @jkpieterse I have another workbook which takes data from VLOOKUP from this multiple sheets. So i need the multiple sheets based on the first column. – Naveen Jun 18 '18 at 08:12
  • Why do you want to switch to VB Script when all the work you do is within Excel? Technically it's possible, but I don't see the point. – FunThomas Jun 18 '18 at 08:16
  • @FunThomas i am trying to automate these things so i wanted a VBS file so it can be called externally without opening the excel files – Naveen Jun 18 '18 at 08:21

2 Answers2

0

You could rewrite the whole code in VBS. However, if it is only for calling the Excel Macro "invisible", the following script may be an alternative. You keep your code within Excel and just call it from VBScript:

Set objExcel = CreateObject("Excel.Application")
objExcel.Visible = false
objExcel.Application.Run "'C:\test1.xlsm'!module1.testSub"

objExcel.DisplayAlerts = False
objExcel.Application.Quit
Set objExcel = Nothing

I would recommend to set the visible-attribute to false only after testing that everything works. Note that this script closes excel without saving anything, so you have to add the save-command into your VBA code.

Update
If you really want to put everything into VBS:

  • remove all types from your variable definitions - basically all variables in VBS are of type variant.
  • Declare all Excel-Constants you need (because VBS doesn't know them)
  • Use the Excel object If you need methods of the application object (eg evaluate)
  • VBScript doesn't support named arguments for function or subroutine calls, so you have to change the syntax there.

This fragment can give you an idea:

option explicit
const xlDown = -4121 
const xlUp = -4162 
dim objExcel
Set objExcel = CreateObject("Excel.Application")

' objExcel.Visible = false
dim wb, ws
set wb = objExcel.Workbooks.open("C:\Test1.xlsm")
with wb
  Set ws = .Sheets("Sheet1")
  dim lastRow
  lastRow = ws.Cells(ws.Rows.Count, 1).End(xlUp).Row

' ...
  dim newSheet
  set newSheet = .Sheets.Add(, .Worksheets(.Worksheets.Count))
  newSheet.name = myarr(i)

 ' ...
end with

' ...
wb.close true     ' At the end, do not forget to save the work
set wb = nothing
Set objExcel = Nothing

Important: If your script fails half the way (and it will during development), make sure that the Excel Instance is closed. Check the task manager if there are suspicious instances of Microsoft Excel running. Also, if at the end of the work a SaveAs-Dialog pops up, it is likely that an previous instance of Excel didn't terminate and now the file was opened in ReadOnly mode. It is not possible to add a On error goto CleanUp to enforce the closure of excel, see https://stackoverflow.com/a/157785/7599798

FunThomas
  • 23,043
  • 3
  • 18
  • 34
  • Thanks @FunThomas.. I dont want to keep the code as a macro. I dont want an xlsm, i want an xlsx. I need help in rewriting the code to VBS. – Naveen Jun 18 '18 at 10:07
  • Start Excel, open a workbook (excel file), access a sheet of it, get the number of lines, add a new sheet, close everything. So basically parts of your VBA script. – FunThomas Jun 18 '18 at 12:31
  • Thank you so much @FunThoma, I will build the VBS around it – Naveen Jun 18 '18 at 12:51
0

Try it like this.

In the code you see four filter examples that you can use, we use example 1 in this macro and I commented the other 3 examples in the code.

1: Criteria in the code (=Netherlands, see the tips below the macro)
2: Filter on ActiveCell value
3: Filter on Range value (D1 in this example)
4: Filter on InputBox value

Sub Copy_With_AutoFilter1()
'Note: This macro use the function LastRow
    Dim My_Range As Range
    Dim CalcMode As Long
    Dim ViewMode As Long
    Dim FilterCriteria As String
    Dim CCount As Long
    Dim WSNew As Worksheet
    Dim sheetName As String
    Dim rng As Range

    'Set filter range on ActiveSheet: A1 is the top left cell of your filter range
    'and the header of the first column, D is the last column in the filter range.
    'You can also add the sheet name to the code like this :
    'Worksheets("Sheet1").Range("A1:D" & LastRow(Worksheets("Sheet1")))
    'No need that the sheet is active then when you run the macro when you use this.
    Set My_Range = Range("A1:D" & LastRow(ActiveSheet))
    My_Range.Parent.Select

    If ActiveWorkbook.ProtectStructure = True Or _
       My_Range.Parent.ProtectContents = True Then
        MsgBox "Sorry, not working when the workbook or worksheet is protected", _
               vbOKOnly, "Copy to new worksheet"
        Exit Sub
    End If

    'Change ScreenUpdating, Calculation, EnableEvents, ....
    With Application
        CalcMode = .Calculation
        .Calculation = xlCalculationManual
        .ScreenUpdating = False
        .EnableEvents = False
    End With
    ViewMode = ActiveWindow.View
    ActiveWindow.View = xlNormalView
    ActiveSheet.DisplayPageBreaks = False

    'Firstly, remove the AutoFilter
    My_Range.Parent.AutoFilterMode = False

    'Filter and set the filter field and the filter criteria :
    'This example filter on the first column in the range (change the field if needed)
    'In this case the range starts in A so Field 1 is column A, 2 = column B, ......
    'Use "<>Netherlands" as criteria if you want the opposite
    My_Range.AutoFilter Field:=1, Criteria1:="=Netherlands"

    'If you want to filter on a cell value you can use this, use "<>" for the opposite
    'This example uses the activecell value
    'My_Range.AutoFilter Field:=1, Criteria1:="=" & ActiveCell.Value

    'This will use the cell value from A2 as criteria
    'My_Range.AutoFilter Field:=1, Criteria1:="=" & Range("A2").Value

    ''If you want to filter on a Inputbox value use this
    'FilterCriteria = InputBox("What text do you want to filter on?", _
     '                              "Enter the filter item.")
    'My_Range.AutoFilter Field:=1, Criteria1:="=" & FilterCriteria

    'Check if there are not more then 8192 areas(limit of areas that Excel can copy)
    CCount = 0
    On Error Resume Next
    CCount = My_Range.Columns(1).SpecialCells(xlCellTypeVisible).Areas(1).Cells.Count
    On Error GoTo 0
    If CCount = 0 Then
        MsgBox "There are more than 8192 areas:" _
             & vbNewLine & "It is not possible to copy the visible data." _
             & vbNewLine & "Tip: Sort your data before you use this macro.", _
               vbOKOnly, "Copy to worksheet"
    Else
        'Add a new Worksheet
        Set WSNew = Worksheets.Add(After:=Sheets(ActiveSheet.Index))

        'Ask for the Worksheet name
        sheetName = InputBox("What is the name of the new worksheet?", _
                             "Name the New Sheet")

        On Error Resume Next
        WSNew.Name = sheetName
        If Err.Number > 0 Then
            MsgBox "Change the name of sheet : " & WSNew.Name & _
                 " manually after the macro is ready. The sheet name" & _
                 " you fill in already exists or you use characters" & _
                 " that are not allowed in a sheet name."
            Err.Clear
        End If
        On Error GoTo 0

        'Copy/paste the visible data to the new worksheet
        My_Range.Parent.AutoFilter.Range.Copy
        With WSNew.Range("A1")
            ' Paste:=8 will copy the columnwidth in Excel 2000 and higher
            ' Remove this line if you use Excel 97
            .PasteSpecial Paste:=8
            .PasteSpecial xlPasteValues
            .PasteSpecial xlPasteFormats
            Application.CutCopyMode = False
            .Select
        End With

        ' If you want to delete the rows that you copy, also use this
        ' With My_Range.Parent.AutoFilter.Range
        '     On Error Resume Next
        '     Set rng = .Offset(1, 0).Resize(.Rows.Count - 1, .Columns.Count) _
        '               .SpecialCells(xlCellTypeVisible)
        '     On Error GoTo 0
        '     If Not rng Is Nothing Then rng.EntireRow.Delete
        ' End With

    End If

    'Close AutoFilter
    My_Range.Parent.AutoFilterMode = False

    'Restore ScreenUpdating, Calculation, EnableEvents, ....
    My_Range.Parent.Select
    ActiveWindow.View = ViewMode
    If Not WSNew Is Nothing Then WSNew.Select
    With Application
        .ScreenUpdating = True
        .EnableEvents = True
        .Calculation = CalcMode
    End With

End Sub


Function LastRow(sh As Worksheet)
    On Error Resume Next
    LastRow = sh.Cells.Find(What:="*", _
                            After:=sh.Range("A1"), _
                            Lookat:=xlPart, _
                            LookIn:=xlValues, _
                            SearchOrder:=xlByRows, _
                            SearchDirection:=xlPrevious, _
                            MatchCase:=False).Row
        On Error GoTo 0
End Function

https://www.rondebruin.nl/win/s3/win006_1.htm

ASH
  • 20,759
  • 19
  • 87
  • 200