如何将非空单元格中的列复制到另一张表格中?

时间:2016-06-30 16:11:29

标签: excel vba

我正在尝试编写一些简单的VBA,我只是想让它遍历我的电子表格中的所有列,如果有值,则将其复制到Sheet2,在那里制作一个长列表。

我在某个地方出错了,我希望它能够让我知道我哪里出错了。

Dim c As Integer
Dim r As Integer
Dim w As Integer
Dim l As Integer
Dim p As Integer
' Define w as the width of the dataset
w = ThisWorkbook.Sheets("Sheet1").Cells(100000, 1).End(xlUp).Column
' Run this for each column 
For c = 1 To w
' Define l as the length of the column
l = ThisWorkbook.Sheets("Sheet1").Cells(c, 100000).End(xlUp).Row
' Run this for each cell in the column
    For r = 1 To l
' If there is something in the cell, copy it across to Sheet 2 Column 1
        If Cells(l, w).Value <> "" Then
            ThisWorkbook.Sheets("Sheet2").Cells(1, p) = Cells(l, w).Value
            p = p + 1
        End If
    Next r
Next c

End Sub

解决方案会很棒,但知道我哪里出错会更好 - 我真的想了解这里的问题是什么。

干杯,

汤姆

1 个答案:

答案 0 :(得分:1)

如果我遇到了您的问题,您的代码中会有一些错误的假设

但首先让我们看看你的实际需要是什么:

Sub main()
    Dim p As Long
    Dim rng As Range, cell as Range 

    With ThisWorkbook
        Set rng = .Worksheets("Sheet1").UsedRange.SpecialCells(xlCellTypeConstants)

        With .Worksheets("Sheet2")
            For Each cell In rng
                p = p  + 1
                .Cells(1, p) = cell.Value
            Next cell
        End With 

    End With 
End Sub 
相关问题