excel VBA帮助,用于根据标题值查找列并将其复制到其他工作表

icnyk63a  于 2023-01-27  发布在  其他
关注(0)|答案(2)|浏览(380)

我有这个基本的代码来查找表中所需的列,并将它们复制到另一个工作表。我的问题是,每次我想修改它不复制&粘贴标题它返回错误。这是我的代码:

Sub CopyColumns()

    Dim wsSource, wsResult As Worksheet
    Dim Name, UniqueId, OperatingStatus As Long
       
    Set wsSource = ThisWorkbook.Sheets("Source")
    Set wsResult = ThisWorkbook.Sheets("Result")
    
    Name = wsSource.Rows(1).Find("#BASEDATA#name").Column
    UniqueId = wsSource.Rows(1).Find("#BASEDATA#uniqueId").Column
    OperatingStatus = wsSource.Rows(1).Find("#BASEDATA#operatingStatus").Column
    
    If Name <> 0 Then
        wsSource.Columns(Name).Copy Destination:=wsResult.Columns(3)
    End If
    If UniqueId <> 0 Then
        wsSource.Columns(UniqueId).Copy Destination:=wsResult.Columns(4)
    End If
    If OperatingStatus <> 0 Then
        wsSource.Columns(OperatingStatus).Copy Destination:=wsResult.Columns(1)
    End If
    
End Sub

有什么想法如何解决它?我尝试是这样复制使用偏移:
If targetColName <> 0 Then
wsSource.Columns(targetColName).Offset(1, 0).Resize(wsSource.Rows.Count - 1).Copy _ Destination:=wsResult.Columns(3).Offset(1, 0)
它给出错误:应用程序定义或对象定义的错误
谢谢!
偏移和调整大小不起作用

qnzebej0

qnzebej01#

您可以将“如果找到则复制列”拆分为单独的子列:

Sub CopyColumns()

    Dim wsSource, wsResult As Worksheet
    
    Set wsSource = ThisWorkbook.Sheets("Source")
    Set wsResult = ThisWorkbook.Sheets("Result")
    
    CopyIfExists wsSource.Rows(1), "#BASEDATA#name", wsResult, 3
    CopyIfExists wsSource.Rows(1), "#BASEDATA#uniqueId", wsResult, 4
    CopyIfExists wsSource.Rows(1), "#BASEDATA#operatingStatus", wsResult, 1
    
End Sub

'Look for `colName` in `headerRow`, and if found copy the whole
'  column to column `destColNum` on `destSheet`
Sub CopyIfExists(headerRow As Range, colName As String, destSheet As Worksheet, destColNum As Long)
    Dim f As Range
    Set f = headerRow.Find(what:=colName, lookat:=xlWhole) 'or xlPart
    If Not f Is Nothing Then
        f.EntireColumn.Copy destSheet.Cells(1, destColNum)
    End If
End Sub

使用find时,在尝试对匹配的单元格执行任何操作之前,应该检查是否找到了匹配项。

euoag5mw

euoag5mw2#

复制列

Option Explicit

Sub CopyColumnsToResult()

    Dim sColNames(): sColNames = Array("#BASEDATA#name", _
        "#BASEDATA#uniqueId", "#BASEDATA#operatingStatus")
    Dim dCols(): dCols = Array(3, 4, 1)

    Dim sws As Worksheet: Set sws = ThisWorkbook.Sheets("Source")
    Dim shrg As Range: Set shrg = sws.Rows(1)
    Dim slCell As Range: Set slCell = shrg.Cells(shrg.Cells.Count) ' last cell
    
    Dim dws As Worksheet: Set dws = ThisWorkbook.Sheets("Result")
    
    Dim shCell As Range, c As Long
    
    For c = LBound(sColNames) To UBound(sColNames)
        Set shCell = shrg.Find(sColNames(c), slCell, xlFormulas, xlWhole)
        If Not shCell Is Nothing Then ' header cell found
            sws.Columns(shCell.Column).Copy dws.Columns(dCols(c))
        End If
    Next c
    
    MsgBox "Columns copied.", vbInformation
    
End Sub

相关问题