excel - 如何将数据从sheet1中的单元格复制到sheet2,循环遍历每个单元格?
问题描述
如何循环浏览 sheet1 以查看该单元格中是否有数据?
- 如果没有数据,则转到下一个单元格。
- 如果下一个单元格中有数据,请将其粘贴到 sheet2 中。
标准是:
- 我不能使用一个设定范围,它会随着 sheet1 中的数据变化而变化。
- 我可以将工作表名称保持为常数,例如 sheet1 和 sheet2。
我找到了一种使用列和/或行的方法,但该代码存在一个主要问题。如果第一个单元格中没有起始数据,它将不会在整个行和/列中复制任何内容。
我发布了用于检查列中数据的代码,但如果没有起始数据,它将跳过整行。
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
解决方案
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
推荐阅读
- html - 如何为 ng-repeat 元素赋予不同的填充样式?
- javascript - 从页面上的多个元素输出文本 - 量角器,Javascript
- regex - egrep 只取带数字的行
- sql - 我可以在 SQLite 表列名中使用问号吗?
- tfs - tfignore 排除包含空格的文件路径不起作用
- android-studio - 无法导入 android studio 3.1.1 库
- python - Python - 列表操作练习
- javascript - 问题生成代码 - 从 DOM 中获取值
- php - 未找到基表或视图:1146 表“Vojodb.users”不存在
- ruby-on-rails - 为 rake 任务编写单元测试