【问题标题】:Copy specific columns from one sheet to another将特定列从一个工作表复制到另一个工作表
【发布时间】:2016-01-31 07:33:02
【问题描述】:

我想将某些列(如 A、B、H)从一张纸复制到另一张纸上,我将此代码复制到了一个模块,但出现“运行时错误 9”。

Sub CopyColumnToWorkbook()
Dim sourceColumn As Range, targetColumn As Range

Set sourceColumn = Workbooks("sheet1.xlsm").Worksheets(1).Columns("A")
Set targetColumn = Workbooks("sheet2.xlsm").Worksheets(1).Columns("A")

sourceColumn.Copy Destination:=targetColumn
End 

我正在处理具有 55 列和 453 行的数据。如何将备用列从一个工作表复制到另一个...示例

我只想要 2010-2011 年的列。在我的数据中.. 2010-2011 年和 2011-2012 年交替排列,例如 2010-2011 年 4 月的一列和 2011-2012 年 4 月的下一列..再次下一列是 2010-2011 年 5 月,下一列是 5 月-2011-2012..等等。

【问题讨论】:

  • 工作簿“sheet1.xlsm”和“sheet2.xlsm”必须在运行该代码之前打开。 “运行时错误 9”是Subscript out of Range。这意味着:集合中没有这样的项目。我怀疑:Workbooks 集合中没有“sheet1.xlsm”或“sheet2.xlsm”。
  • 您的问题暗示您在 1 个工作簿的不同工作表之间复制数据,但您的代码尝试在工作簿(文件)之间复制

标签: excel vba


【解决方案1】:

使用like语句,例如:

Sub Button1_Click()
    Dim sh1 As Worksheet, sh2 As Worksheet
    Dim col As Long, rng As Range, c As Range, cRng As Range, cRws As Long, col2 As Long

    Set sh1 = Sheets("Sheet1")
    Set sh2 = Sheets("Sheet2")

    With sh1
        col = .Cells(1, .Columns.Count).End(xlToLeft).Column
        Set rng = .Range(.Cells(1, 1), .Cells(1, col))

        For Each c In rng.Cells

            If c Like "*2010-2011*" Then
                cRws = .Cells(.Rows.Count, c.Column).End(xlUp).Row
                Set cRng = .Range(.Cells(1, c.Column), .Cells(cRws, c.Column))

                cRng.Copy sh2.Cells(1, sh2.Columns.Count).End(xlToLeft).Offset(, 1)
            End If

        Next c
    End With

    sh2.Columns("A:A").EntireColumn.Delete Shift:=xlToLeft
    sh2.Cells.EntireColumn.AutoFit

End Sub

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多