VBA 根据列 header 名称复制列的 UsedRange

VBA copy UsedRange of a column based on column header name

我正在尝试根据 column-name 将数据从一个工作表复制到另一个工作表。在源工作表中,数据从 A1 开始。在目标工作表中,数据应粘贴到 A11 行而不是 A1 行。如果我使用 EntireColumn.Copy,我会收到有关源副本区域和目标副本区域不相同的错误。我遇到了 UsedRange 属性,但我无法将其应用到我的场景中

    For Each columnName In allColumns
    'call a function to get the column to copy 
    If columnToCopy > 0 Then
        columnName.Offset(1, 0).EntireColumn.Copy Destination:=ws2.Cells(11, columnToCopy)
    End If
Next

在上面的代码片段中,不想使用 'EntireColumn'。我只想要有数据的列。变量 columnName 是例如 'Person ID'

最好的方法是什么?

谢谢。

这是一个典型的方法:

    For Each ColumnName In allColumns
        If columnToCopy > 0 Then
            With ColumnName.Parent
                .Range(ColumnName.Offset(1, 0), .Cells(.Rows.Count, ColumnName.Column).End(xlUp)).Copy _
                              Destination:=ws2.Cells(11, columnToCopy)
            End With
        End If
    Next

假设 allColumns 是 single-cell ranges/column headers.

的 collection

Copy/Paste列

信息不足,无法给出准确答案,因此您可以考虑研究以下场景。

代码

Option Explicit

Sub TESTdetermineColumnNumber()
    
    ' Define constants. Should be more.

    ' Define Criteria.
    Const Criteria As String = "Total"
    ' Define Header Row.
    Const hRow As Long = 1

    ' Define Copy Range (Column Range)

    ' Define Source Worksheet.
    Dim ws As Worksheet
    Set ws = ThisWorkbook.Worksheets("Sheet1")
    ' Define Header Row Range.
    Dim RowRange As Range
    Set RowRange = ws.Rows(hRow)
    ' Determine Column Number.
    Dim ColumnNumber As Long
    ColumnNumber = determineColumnNumber(RowRange, Criteria)
    ' Validate Column Number.
    If ColumnNumber = 0 Then
        Exit Sub
    End If
    ' Determine Last Row.
    Dim LastRow As Long
    LastRow = ws.Cells(ws.Rows.Count, ColumnNumber).End(xlUp).Row
    ' Define First Data Row Number.
    Dim FirstRow As Long
    FirstRow = hRow + 1
    ' Define Column Range.
    Dim ColumnRange As Range
    Set ColumnRange = ws.Cells(FirstRow, ColumnNumber) _
                        .Resize(LastRow - FirstRow + 1)

    ' Define Paste Range.

    ' Define Destination Worksheet.
    Dim ws2 As Worksheet
    Set ws2 = ThisWorkbook.Worksheets("Sheet2")
    ' Define Destination Column.
    Dim columnToCopy As Long
    columnToCopy = 2
    ' Define Paste Range.
    Dim PasteRange As Range
    Set PasteRange = ws2.Cells(11, columnToCopy)

    ' Copy/Paste.

    ' Copy values, formulas and formats.
    ColumnRange.Copy Destination:=PasteRange
    ' It is more efficient if you need only values to use the following:
    PasteRange.Resize(ColumnRange.Rows.Count).Value = ColumnRange.Value
    
End Sub

Function determineColumnNumber(RowRange As Range, _
                               Criteria As String) _
         As Long
    Dim Temp As Variant
    Temp = Application.Match(Criteria, RowRange, 0)
    If Not IsError(Temp) Then
        determineColumnNumber = Temp
    End If
End Function