我有一个VBA代码,它可以根据所选列中的变量将我的数据分割成单独的工作表。这很好用,但我有几个变量,我想在同一张工作表中,dispite有不同的名称。
示例:
在B列中,我有公司A、B、C、D和E。这些公司被分解到不同的工作表中。但是,公司A和C具有相同的母公司,因此应该位于同一工作表中。
如果我在文件中包含了一个类似下面的表,我如何将其添加到代码中?
| 色谱柱A|B栏|
| - ------|- ------|
| A公司|"世界"组|
| B公司|"其他"组|
| C公司|"世界"组|
| D公司|"其他"组|
| E公司|"其他"组|
Sub Step1_split()
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
'This macro splits data into multiple worksheets based on the variables on a column found in Excel.
'An InputBox asks you which columns you'd like to filter by, and it just creates these worksheets.
Application.ScreenUpdating = False
vcol = Application.InputBox(prompt:="Which column would you like to filter by?", title:="Filter column", Default:="2", Type:=1)
Set ws = ActiveSheet
lr = ws.Cells(ws.Rows.Count, vcol).End(xlUp).Row
title = "A1"
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
Application.ScreenUpdating = True
End Sub
我试过在代码中添加一个IF公式,但不知道如何操作。
1条答案
按热度按时间nfg76nw01#
为关系表创建一个名为“组”的工作表。生成一个用于筛选条件的公司名称数组。