Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/sorting/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Excel 基于单元格值复制行并粘贴到具有相同单元格值名称的新工作表上_Excel_Vba - Fatal编程技术网

Excel 基于单元格值复制行并粘贴到具有相同单元格值名称的新工作表上

Excel 基于单元格值复制行并粘贴到具有相同单元格值名称的新工作表上,excel,vba,Excel,Vba,我有一份数据表,其中包含一份有3列的员工名单 COLUMN A - DEPARTMENT COLUMN B - EMPCODE COLUMN C - EMPNAME 以下是示例数据: 我想根据A列-部门将此表的内容拆分,并将其放在不同的表上,新表将命名为A列中的部门名称 最终结果应该是这样的: 此代码检查每一行。如果列A中的单元格与下面的单元格相等,则选择该行 Sub CopyRows() Dim rngMyRange As Range, rngCell As Range

我有一份数据表,其中包含一份有3列的员工名单

COLUMN A - DEPARTMENT
COLUMN B - EMPCODE
COLUMN C - EMPNAME
以下是示例数据:

我想根据A列-部门将此表的内容拆分,并将其放在不同的表上,新表将命名为A列中的部门名称

最终结果应该是这样的:

此代码检查每一行。如果列A中的单元格与下面的单元格相等,则选择该行

Sub CopyRows()

    Dim rngMyRange As Range, rngCell As Range
    With Worksheets("DATA")
     Set rngMyRange = .Range(.Range("a1"), .Range("A65536").End(xlUp))

     For Each rngCell In rngMyRange
            If rngCell.Value = rngCell.Offset(1, 0).Value Then
            rngCell.EntireRow.Select
         End If

     Next
         Selection.Copy
         Sheets.Add After:=ActiveSheet
         Rows("1:1").Select
         Selection.Insert Shift:=xlDown
         ActiveSheet.Name = Range("A1")
 End With

 End Sub

如何在检查列A中的单元格值时保留选择并添加更多选定行?

您提出了一个非常好的问题。它清楚地描述了起点和目标。您拥有的代码是通向答案的良好开端。然而,我并没有像你想的那样把一堆行组合在一起,因为我不知道怎么做。我所做的是循环遍历数据范围,然后一次处理一行。如果目标工作表存在,我会在最后一行之后插入该行。如果目标工作表不存在,我将按照您的方式创建新工作表。使用调试器逐步完成此操作,您将能够看到它是如何工作的

Sub CopyRows()

Dim rngMyRange As Range, rngCell As Range
Dim sht As Worksheet
Dim LastRow As Long
Dim SheetName As String



With Worksheets("DATA")
Set rngMyRange = .Range(.Range("a1"), .Range("A65536").End(xlUp))

    For Each rngCell In rngMyRange

        rngCell.EntireRow.Select

        Selection.Copy

        If (WorksheetExists(rngCell.Value)) Then
            SheetName = rngCell.Value
            Sheets(SheetName).Select
            Set sht = ThisWorkbook.Worksheets(SheetName)
            LastRow = sht.Cells(sht.Rows.Count, "A").End(xlUp).row
            Rows(LastRow + 1).Select
            Selection.Insert Shift:=xlDown
        Else
            Sheets.Add After:=ActiveSheet
            Rows("1:1").Select
            Selection.Insert Shift:=xlDown
            ActiveSheet.Name = rngCell.Value
        End If


        'Go back to the DATA sheet
        Sheets("DATA").Select
    Next

End With

End Sub

Function WorksheetExists(sName As String) As Boolean
    WorksheetExists = Evaluate("ISREF('" & sName & "'!A1)")
End Function
您可以按如下方式使用范围对象和方法:

Option Explicit

Sub CopyRows()
    Dim rngCell As Range
    Dim depSheet As Worksheet

    With Worksheets("DATA") '<--|refer to data sheet
        .Rows(1).Insert '<--|insert a temporary header row: it'll be used for AutoFilter() method and eventually deleted
        .Cells(1, 1).value = "Department" '<--| place a dummy header in the temporary header row
        With .Range("A1", .Cells(.Rows.Count, 1).End(xlUp)).Offset(, .UsedRange.Columns.Count) '<--| refer to a "helper" column out of the used range and limited to column "A" last non empty row
            .value = .Offset(, -.Parent.UsedRange.Columns.Count).value '<--| duplicate departments (column "A") values in helper one
            .RemoveDuplicates Columns:=Array(1), header:=xlYes '<--| leave only departments unique values in "helper" column
            For Each rngCell In .Range("A2:A" & .Cells(.Rows.Count, 1).End(xlUp).Row) '<--|loop through "helper" column departments unique values
                Set depSheet = GetSheet(.Parent.Parent, rngCell.value) '<--|get or add the worksheet corresponding to current department
                With .Offset(, -.Parent.UsedRange.Columns.Count + 1) '<--|refer to departments column
                    .AutoFilter field:=1, Criteria1:=rngCell.value '<--| filter it on current department value
                    With .Offset(1).Resize(.Rows.Count - 1).SpecialCells(xlCellTypeVisible) '<--| refer to department filtered cells
                        depSheet.Cells(depSheet.Rows.Count, 1).End(xlUp).Offset(1).Resize(.Cells.Count, 3).value = .Resize(, 3).value '<--|copy their values along with columns "B" and "C" ones into first empty row of the corresponding worksheet
                    End With
                End With
            Next rngCell
            .ClearContents '<--| clear "helper" column
        End With
        .AutoFilterMode = False
        .Rows(1).Delete '<--| delete temporary header row
    End With
 End Sub

Function GetSheet(wb As Workbook, shtName As String) As Worksheet
    On Error Resume Next
    Set GetSheet = wb.Worksheets(shtName) '<--| try and set a sheet with passed name
    On Error GoTo 0
    If GetSheet Is Nothing Then '<--| if there weas no such sheet...
        Set GetSheet = wb.Worksheets.Add(After:=ActiveSheet) '<--|... add a new sheet
        With GetSheet
            .Name = shtName '<--|rename it after passed name
            .Range("A1:C1").value = Array("DEPARTMENT", "EMPCODE", "EMPNAME") '<--| add headers
        End With
    End If
End Function
选项显式
子复制行()
Dim rngCell As范围
将工作表作为工作表

使用工作表(“数据”)”感谢您的回复。事实上,我发现了一个非常好的代码,完全符合我的要求,但我忘了记下参考网站。如果有人感兴趣,下面是代码:

    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("DATA")
    lr = ws.Cells(ws.Rows.Count, vcol).End(xlUp).Row
    title = "A1:J1"
    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
子解析_数据()
变暗lr为长
将ws设置为工作表
Dim vcol,i作为整数
如长
Dim myarr作为变异体
将标题设置为字符串
作为整数的Dim titlerow
vcol=1
设置ws=图纸(“数据”)
lr=ws.Cells(ws.Rows.Count,vcol).End(xlUp).Row
title=“A1:J1”
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
端接头

我创建此VBA是为了根据第三张图纸(条件)中给出的条件数据将数据从一张图纸(源)复制到另一张图纸(目标):

但是艾琳, 如果我们需要复制E列的单元格值,而不是A列并粘贴到新的工作表上,那么您的ref代码仍然会列出A列的值。。。。。。! 因此,我们只需要在上面修改的第9行中更改vcol=5,以绕过对图纸名称所允许的最大长度的限制。它将名称的前13个字符和后13个字符连接在一起,中间有4个点

Option Explicit

Sub CopyRows()
    Dim rngCell As Range
    Dim depSheet As Worksheet
    
    Application.ScreenUpdating = False
    Application.Calculation = xlCalculationManual

    With Worksheets("DATA") '<--|refer to data sheet
        .Rows(1).Insert '<--|insert a temporary header row: it'll be used for AutoFilter() method and eventually deleted
        .Cells(1, 1).Value = "Table_Name" '<--| place a dummy header in the temporary header row
        With .Range("A1", .Cells(.Rows.count, 1).End(xlUp)).Offset(, .UsedRange.Columns.count) '<--| refer to a "helper" column out of the used range and limited to column "A" last non empty row
            .Value = .Offset(, -.Parent.UsedRange.Columns.count).Value '<--| duplicate departments (column "A") values in helper one
            .RemoveDuplicates Columns:=Array(1), Header:=xlYes '<--| leave only departments unique values in "helper" column
            For Each rngCell In .Range("A2:A" & .Cells(.Rows.count, 1).End(xlUp).Row) '<--|loop through "helper" column departments unique values
                Set depSheet = GetSheet(.Parent.Parent, rngCell.Value) '<--|get or add the worksheet corresponding to current department
                With .Offset(, -.Parent.UsedRange.Columns.count + 1) '<--|refer to departments column
                    .AutoFilter field:=1, Criteria1:=rngCell.Value '<--| filter it on current department value
                    With .Offset(1).Resize(.Rows.count - 1).SpecialCells(xlCellTypeVisible) '<--| refer to department filtered cells
                        depSheet.Cells(depSheet.Rows.count, 1).End(xlUp).Offset(1).Resize(.Cells.count, 3).Value = .Resize(, 3).Value '<--|copy their values along with columns "B" and "C" ones into first empty row of the corresponding worksheet
                    End With
                End With
            Next rngCell
            .ClearContents '<--| clear "helper" column
        End With
        .AutoFilterMode = False
        .Rows(1).Delete '<--| delete temporary header row
    End With
    
    Application.ScreenUpdating = True
    Application.Calculation = xlCalculationAutomatic
 End Sub

Function GetSheet(wb As Workbook, shtName As String) As Worksheet
    On Error Resume Next
    Set GetSheet = wb.Worksheets(shtName) '<--| try and set a sheet with passed name
    On Error GoTo 0
    If GetSheet Is Nothing Then '<--| if there weas no such sheet...
        Dim count As Long
        count = Len(shtName)
        Dim newName As String
        If count > 30 Then
            newName = Left(shtName, 13) & "...." & Right(shtName, 13)
        Else
            newName = shtName
        End If
        Set GetSheet = wb.Worksheets.Add(After:=ActiveSheet) '<--|... add a new sheet
        With GetSheet
            .Name = newName '<--|rename it after passed name
            .Range("A1:C1").Value = Array("DEPARTMENT", "EMPCODE", "EMPNAME") '<--| add headers
        End With
    End If
End Function
选项显式
子复制行()
Dim rngCell As范围
将工作表作为工作表
Application.ScreenUpdating=False
Application.Calculation=xlCalculationManual

关于工作表(“数据”)@Eileen:你通过了吗?这应该是最重要的答案。这应该是公认的答案。可惜@Eileen似乎对这个问题不再感兴趣了。我修改了
GetSheet
函数,以绕过下面我的答案中工作表名称的最大长度限制。在错误恢复下一步时,
是一个错误的代码。你试过我的吗?
Option Explicit

Sub CopyRows()
    Dim rngCell As Range
    Dim depSheet As Worksheet
    
    Application.ScreenUpdating = False
    Application.Calculation = xlCalculationManual

    With Worksheets("DATA") '<--|refer to data sheet
        .Rows(1).Insert '<--|insert a temporary header row: it'll be used for AutoFilter() method and eventually deleted
        .Cells(1, 1).Value = "Table_Name" '<--| place a dummy header in the temporary header row
        With .Range("A1", .Cells(.Rows.count, 1).End(xlUp)).Offset(, .UsedRange.Columns.count) '<--| refer to a "helper" column out of the used range and limited to column "A" last non empty row
            .Value = .Offset(, -.Parent.UsedRange.Columns.count).Value '<--| duplicate departments (column "A") values in helper one
            .RemoveDuplicates Columns:=Array(1), Header:=xlYes '<--| leave only departments unique values in "helper" column
            For Each rngCell In .Range("A2:A" & .Cells(.Rows.count, 1).End(xlUp).Row) '<--|loop through "helper" column departments unique values
                Set depSheet = GetSheet(.Parent.Parent, rngCell.Value) '<--|get or add the worksheet corresponding to current department
                With .Offset(, -.Parent.UsedRange.Columns.count + 1) '<--|refer to departments column
                    .AutoFilter field:=1, Criteria1:=rngCell.Value '<--| filter it on current department value
                    With .Offset(1).Resize(.Rows.count - 1).SpecialCells(xlCellTypeVisible) '<--| refer to department filtered cells
                        depSheet.Cells(depSheet.Rows.count, 1).End(xlUp).Offset(1).Resize(.Cells.count, 3).Value = .Resize(, 3).Value '<--|copy their values along with columns "B" and "C" ones into first empty row of the corresponding worksheet
                    End With
                End With
            Next rngCell
            .ClearContents '<--| clear "helper" column
        End With
        .AutoFilterMode = False
        .Rows(1).Delete '<--| delete temporary header row
    End With
    
    Application.ScreenUpdating = True
    Application.Calculation = xlCalculationAutomatic
 End Sub

Function GetSheet(wb As Workbook, shtName As String) As Worksheet
    On Error Resume Next
    Set GetSheet = wb.Worksheets(shtName) '<--| try and set a sheet with passed name
    On Error GoTo 0
    If GetSheet Is Nothing Then '<--| if there weas no such sheet...
        Dim count As Long
        count = Len(shtName)
        Dim newName As String
        If count > 30 Then
            newName = Left(shtName, 13) & "...." & Right(shtName, 13)
        Else
            newName = shtName
        End If
        Set GetSheet = wb.Worksheets.Add(After:=ActiveSheet) '<--|... add a new sheet
        With GetSheet
            .Name = newName '<--|rename it after passed name
            .Range("A1:C1").Value = Array("DEPARTMENT", "EMPCODE", "EMPNAME") '<--| add headers
        End With
    End If
End Function