首页 > 解决方案 > 如何将数据从sheet1中的单元格复制到sheet2,循环遍历每个单元格?

问题描述

如何循环浏览 sheet1 以查看该单元格中是否有数据?

标准是:

我找到了一种使用列和/或行的方法,但该代码存在一个主要问题。如果第一个单元格中没有起始数据,它将不会在整个行和/列中复制任何内容。

我发布了用于检查列中数据的代码,但如果没有起始数据,它将跳过整行。

Sub CopytoImport()
    Dim wb As Workbook
    Dim iCol As Long
    Dim ws As Worksheet

    Sheets("sheet2").Cells.ClearContents

    ' Loop through the column
    For iCol = 1 To 22 ' Call out columns I cannot set this every time it should look threw all cells
        With Worksheets("sheet1").Columns(iCol)
            ' Check tht column is not empty
            If .Cells(1, 1).Value = "" Then
                'Nothing in this column
                'Do nothing
            Else
                ' Copy the coumn to te destination
                Range(.Cells(1, 1), .End(xlDown)).Copy _
                    Destination:=Worksheets("sheet2").Columns(iCol).Cells(1, 1)
            End If
        End With
    Next iCol

    ActiveWorkbook.Save
End Sub


Function runcode()
    Call CopytoImport
End Function

标签: excelvba

解决方案


Cells(1, 1)只是RANGE.("A1")您只在代码中对这个单元格进行操作。您需要Cells(1, iCol)考虑在循环期间您所在的列。

您可能还需要一个嵌套循环,因为您也在循环遍历行。嵌套循环的基本轮廓如下。请注意,Cells(1,1)替换为 i 和 j 代表我们所在的行和列。这可能不是实现您想要的结果的最快方法,但听起来这就是您寻求帮助的方式。当您粘贴数据时,您还需要在 Sheet2 中定义一个 lastrow(末尾带有 + 1 以获取下一个空白单元格)。你可以把它放在循环开始穿过行的地方。这样,每次将数据移动到该工作表时,都会重新计算 sheet2 的最后一行。我不打算重新编写你的代码,因为你说它不完整,但这里有一个可以帮助你的例子。

For j = 5 To lastcolumn

    For i = 5 To lastrow

        Dim lastrow2 As Long
        lastrow2 = Worksheets(1).Range("A" & Rows.Count).End(xlUp).Row + 1

        If Worksheets(2).Cells(i, j).Value <> 0 Then
        Worksheets(1).Range("C" & lastrow2).Value = Worksheets(2).Cells(i, j).Value
        Worksheets(1).Range("B" & lastrow2).Value = Worksheets(2).Cells(2, j).Value

        End If

    Next i

Next j

要找到你的最后一根:

dim lastrow as long
lastrow = Range("A" & rows.count).End(xlup).Row ' or whatever column contains the data

找到你的最后一列

Dim lastcolumn As Long

lastcolumn = Worksheets(2).Cells(2, Columns.Count).End(xlToLeft).Column

推荐阅读