首页 > 解决方案 > 将不同的列堆叠成不同工作表上的一列

问题描述

我想将从 C5 开始的所有填充单元格复制到不同工作表的 F 列。

我参考了另一篇帖子:Excel - 将多列合并为一列 根据我的需要修改了代码。

    Sub CombineColumns()
Dim Range1 As Range, iCol As Long, Range2 As Range, Check As Range, wks As Worksheets

Set Range1 = wks("T(M)").Range(Cells(5, 3), Cells(Cells(5, 3).End(xlDown).Row, Cells(5, 3).End(xlToRight).Column))
Set Check = wks("csv").Range("F1")
If IsEmpty(Check.Value) = True Then
Set Range2 = Check
Else
LastRow = wks("csv").Range("F" & Rows.Count).End(xlUp).Row
Set Range2 = wks("csv").Cells(LastRow, 6).Offset(1, 0)
End If
For iCol = 3 To Range1.Columns.Count
    wks("T(M)").Range(Cells(5, iCol), Cells(Range1.Columns(iCol).Rows.Count, iCol)).Copy
    wks("csv").Range2.PasteSpecial Paste:=xlPasteValuesAndNumberFormats
Next iCol
End Sub

但我一直收到错误消息

“对象不支持此方法或属性”

在粘贴的步骤。在我尝试限定所有范围后,它说我没有设置对象变量。

十分感谢你的帮助!

标签: excelvba

解决方案


这个怎么样?

Sub Transposes()

    ' Example just for hardcoded data
    Dim inputRange As Range
    Set inputRange = Sheets("Sheet1").Range("C5:F10").SpecialCells(xlCellTypeConstants)

    Dim outputCell As Range
    Set outputCell = Sheets("Sheet2").Range("A1")

    Dim cell As Range
    For Each cell In inputRange
        Dim offset As Long
        outputCell.offset(offset).Value = cell.Value
        offset = offset + 1
    Next cell

End Sub

将 ColumnF 中的最后一行设置为您想要的任何内容,如果动态更改,只需使用多种技术中的任何一种即可找到您需要复制/粘贴的最后一个单元格。


推荐阅读