【问题标题】:Copy Common Columns to separate sheet将公共列复制到单独的工作表
【发布时间】:2017-07-28 07:59:13
【问题描述】:

我尝试使用以下代码将整列从一页复制到另一页。

我有一个常见的标题是六月分散在工作表中,我只想复制列,标题名称为“六月”在单独的工作表中一个接一个。

EG 如果 Col A、C、L、M 的列标题为 June,则在下一张表中,这些应仅复制为 A、B、C、D。

Sheets("sheet1").Select 
June = WorksheetFunction.Match("Description", Rows("1:1"), 0) 

Sheets("sheet1").Columns(June).Copy Destination:=Sheets("sheet2").Range("A1") 

【问题讨论】:

  • 使用第1行的Find函数,设置Range,如果Find成功,则获取Column属性

标签: excel vba


【解决方案1】:

以下可能会有所帮助:

Option Explicit

Sub Demo()
    Dim srcSht As Worksheet, destSht As Worksheet
    Dim headerRng As Range, cel As Range, copyRng As Range
    Dim lastCol As Long, col As Long

    Set srcSht = ThisWorkbook.Sheets("Sheet1")      'Sheet1
    Set destSht = ThisWorkbook.Sheets("Sheet2")     'Sheet2

    lastCol = srcSht.Cells(1, srcSht.Columns.Count).End(xlToLeft).Column    'last column of Sheet1

    With srcSht
        For Each cel In .Range(.Cells(1, 1), .Cells(1, lastCol))  'loop through each header name in Sheet1
            If cel = "June" Then                            'check header is "June"
                If copyRng Is Nothing Then                  'assign range to copy
                    Set copyRng = .Columns(cel.Column)
                Else
                    Set copyRng = Union(copyRng, .Columns(cel.Column))
                End If
            End If
        Next cel
    End With
    copyRng.Copy destSht.Range("A1")                'copy and paste desired columns
End Sub

【讨论】:

  • 不错 + 你可以使用With srcSht 来缩短和清理你的代码
  • 在copyRng.Copy destSht.Range("A1")中显示错误。
  • 运行时错误 - 91 对象变量或未设置块变量
  • @NehaKohli - 你能调试和检查copyRng.address
  • @NehaKohli - Sheet1 的标题在哪一行?并确保至少有一列带有标题 June。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-08-14
  • 2017-06-27
  • 1970-01-01
相关资源
最近更新 更多