excel - 根据值类型从 table 复制值

excel - Copy values from table depending on value type

我在 sheet1(导出)中有以下 table:

-----------------------------
| col1 | col2 |..cN..|ctr_type|
-----------------------------
|value |value |valueN|CtrType1|
-----------------------------
|value |value |valueN|CtrType2|
-----------------------------
|value |value |valueN|CtrType3|
-----------------------------
|value |value |valueN|CtrType1|
-----------------------------
|value |value |valueN|CtrType3|
-----------------------------
|value |value |valueN|CtrType2|
-----------------------------

其中 ctr_type 是必须复制传入值的 sheet 的名称。

所以我的问题是:如何在传入 sheet 中复制值。

一个预期的输出是 table 中在列 ctr_type 中具有 CtrType1 的所有值将被复制到名为 CtrType1 的现有 sheet 中。

谢谢!

可以使用类似下面的内容。假设您的数据有 headers 并从第 1 列开始,并且 table 右侧没有数据。否则,更改确定最后一列的方法。

我有帮助函数来查找最后一行和最后一列。我循环最后一列以获取存储在字典中的唯一 sheet 名称,同时将 sheet 名称左侧的范围添加到字典中。如果 sheet 名称作为字典中的键存在,我将使用 Union 将当前范围添加到为该 sheet 名称找到的现有行的左侧。

我 re-loop 字典使用 sheet 名称键将值写入适当的 sheet。您应该添加错误处理,例如如果 sheet 不存在怎么办?

Option Explicit
Public Sub WriteValues()
    Dim rng As Range, ws As Worksheet, loopRange As Range, sheetDict As Object
    Set ws = ActiveSheet: Set sheetDict = CreateObject("Scripting.Dictionary")
    With ws
        Set loopRange = Range(.Cells(2, GetLastColumn(ws, 1)), .Cells(GetLastRow(ws, 1), GetLastColumn(ws, 1)))
        For Each rng In loopRange
            If Not sheetDict.Exists(rng.Value) Then
                Dim tempRange As Range
                Set tempRange = .Range(.Cells(rng.Row, 1), .Cells(rng.Row, GetLastColumn(ws, 1) - 1))
                sheetDict.Add rng.Value, tempRange.Address
            Else
                Set tempRange = Union(.Range(sheetDict(rng.Value)), .Range(.Cells(rng.Row, 1), .Cells(rng.Row, GetLastColumn(ws, 1) - 1)))
                sheetDict(rng.Value) = tempRange.Address
            End If
        Next rng
        For Each rng In loopRange
            Set tempRange = .Range(sheetDict(rng.Value))
            If Not tempRange Is Nothing Then
                tempRange.Copy Worksheets(rng.Value).Range("A" & GetLastRow(Worksheets(rng.Value), 1))
            End If
        Next rng
    End With
End Sub

Public Function GetLastColumn(ByVal ws As Worksheet, Optional ByVal rowNumber As Long = 1) As Long
    With ws
        GetLastColumn = .Cells(rowNumber, .Columns.Count).End(xlToLeft).Column
    End With
End Function

Public Function GetLastRow(ByVal ws As Worksheet, Optional ByVal columnNumber As Long = 1) As Long
    With ws
        GetLastRow = .Cells(.Rows.Count, columnNumber).End(xlUp).Row
    End With
End Function