基于Excel中的列将数据拆分为多个工作表的VB脚本

基于Excel中的列将数据拆分为多个工作表的VB脚本,excel,vba,vbscript,Excel,Vba,Vbscript,我有一个数据完全混合的excel文件(第1列,名称)。我想根据第一列,即名称,将数据拆分为同一工作簿中的多个工作表。我找到了解决这个问题的VBA,但我想这是VB脚本。请帮忙。提前谢谢 `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

我有一个数据完全混合的excel文件(第1列,名称)。我想根据第一列,即名称,将数据拆分为同一工作簿中的多个工作表。我找到了解决这个问题的VBA,但我想这是VB脚本。请帮忙。提前谢谢

`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`
`Sub parse_data()
变暗lr为长
将ws设置为工作表
Dim vcol,i作为整数
如长
Dim myarr作为变异体
将标题设置为字符串
作为整数的Dim titlerow
vcol=1
设置ws=Sheets(“ZPC_统计数据”)
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)=“唯一”
对于i=2至lr
出错时继续下一步
如果ws.Cells(i,vcol)“”和Application.WorksheetFunction.Match(ws.Cells(i,vcol),ws.Columns(icol),0)=0,则
ws.Cells(ws.Rows.Count,icol).End(xlUp).Offset(1)=ws.Cells(i,vcol)
如果结束
下一个
myarr=Application.WorksheetFunction.Transpose(ws.Columns(icol).SpecialCells(xlCellTypeConstants))
ws.Columns(icol).清除
对于i=2至UBound(myarr)
ws.Range(title).AutoFilter字段:=vcol,标准1:=myarr(i)&“”
如果不进行评估(“=ISREF(”&myarr(i)&“!A1)”),则
Sheets.Add(之后:=工作表(Worksheets.Count)).Name=myarr(i)和“”
其他的
工作表(myarr(i)和“”)。移动后:=工作表(Worksheets.Count)
如果结束
ws.Range(“A”&标题栏&“:A”&标题栏).EntireRow.Copy图纸(myarr(i)&“).Range(“A1”)
图纸(myarr(i)和“”).Columns.AutoFit
下一个
ws.AutoFilterMode=False
ws.Activate
端接头`

您可以在VBS中重写整个代码。但是,如果仅用于调用Excel宏“不可见”,则以下脚本可能是一种替代方法。将代码保存在Excel中,只需从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
我建议只有在测试一切正常后,才将
visible
-属性设置为
false
。请注意,此脚本关闭excel而不保存任何内容,因此必须将save命令添加到VBA代码中

更新
如果您确实想将所有内容放入VBS:

  • 从变量定义中删除所有类型-基本上是所有类型 VBS中的变量类型为
    variant
  • 声明所需的所有Excel常量(因为VBS不知道它们)
  • 如果需要,请使用Excel对象 需要
    应用程序
    对象的方法(例如
    评估
  • VBScript不支持函数或子例程调用的命名参数,因此 你必须改变那里的语法
这个片段可以给你一个想法:

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
重要信息:如果脚本中途失败(并且在开发过程中会失败),请确保关闭Excel实例。检查任务管理器是否存在运行
Microsoft Excel
的可疑实例。此外,如果在工作结束时弹出一个
SaveAs
-对话框,则可能是以前的Excel实例没有终止,现在文件以只读模式打开。无法在错误转到清理时添加
,若要强制关闭excel,请参见这样尝试

在代码中,您可以看到四个可以使用的过滤器示例,我们在这个宏中使用示例1,我对代码中的其他3个示例进行了注释

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
1:代码中的标准(=荷兰,请参见宏下面的提示)
2:根据ActiveCell值进行筛选
3:过滤范围值(本例中为D1)
4:输入框值上的过滤器
带有自动过滤器1()的子副本
'注意:此宏使用函数LastRow
将我的_范围变暗为范围
暗淡的CalcMode与长
将视图模式变暗为长
作为字符串的Dim FilterCriteria
长帐
新建为工作表
将sheetName设置为字符串
变暗rng As范围
'在ActiveSheet上设置筛选范围:A1是筛选范围的左上角单元格
'并且第一列的标题D是筛选范围中的最后一列。
'您还可以将图纸名称添加到代码中,如下所示:
'工作表(“表1”)。范围(“A1:D”和最后一行(工作表(“表1”))
'使用此选项时,在运行宏时,无需工作表处于活动状态。
设置My_Range=Range(“A1:D”和LastRow(ActiveSheet))
My_Range.Parent.Select
如果ActiveWorkbook.ProtectStructure=True或_
My_Range.Parent.ProtectContents=则为True
MsgBox“抱歉,工作簿或工作表受保护时不工作”_
vbOKOnly,“复制到新工作表”
出口接头
如果结束
'更改屏幕更新、计算、启用事件。。。。
应用
CalcMode=.Calculation
.Calculation=xlCalculationManual
.ScreenUpdate=False
.EnableEvents=False
以
ViewMode=ActiveWindow.View
ActiveWindow.View=xlNormalView
ActiveSheet.DisplayPageBreaks=False
'首先,卸下自动过滤器
My_Range.Parent.AutoFilterMode=False
'筛选并设置筛选字段和筛选条件:
'此示例筛选器位于范围中的第一列(如果需要,请更改字段)
'在这种情况下,范围从so字段开始,1是A列,2=B列。。。。。。
如果您想要相反的结果,请使用“荷兰”作为标准
My_Range.AutoFilter字段:=1,准则1:==荷兰
'如果要对单元格值进行筛选,可以使用此选项,使用“”作为相反的选项
'此示例使用activecell值
'My_Range.AutoFilter字段:=1,Criteria1:=“=”&ActiveCell.Value
'这将使用A2中的单元格值作为标准
'My_Range.AutoFilter字段:=1,Criteria1:=“=”&范围(“A2”).值
''如果要对Inputbox值进行筛选,请使用此
'FilterCriteria=InputBox(“您想筛选什么文本?”_
““输入筛选项。”)
'My_Range.AutoFilter字段:=1,准则1:=“=”&筛选准则
'检查是否有超过8192个区域(Excel可以复制的区域限制)
帐户=0
出错时继续下一步
CCount=我的范围.列(1).特殊单元格