我如何使循环引用下一个单元格?

时间:2019-03-08 19:19:50

标签: excel vba

下面的代码会将文本从一张纸复制并插入到我想要的另一张纸上。但是,我不知道如何编写循环以使其适用于其余数据。新手在这里,所以可能很简单。如果代码适用,它只需要检查WS1工作表的下一行并输入WS2工作表。

我已注释掉我写的无效的循环。我尝试了startitem = startitem + 1和startitem = startitem.offset(1),但都无法正常工作。

Sub transferdata()

Application.ScreenUpdating = False

Dim ws1     As Worksheet
Dim ws2     As Worksheet
Dim startrow As Range

Dim startpremium As Range
Dim startitem As Range
Dim itemcount As Range


Set ws1 = Sheets("Input")
Set ws2 = Sheets("PakEmail")
Set startrow = ws2.Range("B18")
Set startpremium = ws2.Range("E18")
Set startitem = ws1.Range("D11")
Set itemcount = ws1.Range("D44")
Set copyname = ws1.Range("B11")
Set copypremium = ws1.Range("D11")

'Let X = 0

'Do While X <= itemcount

If startitem <> 0 Then
 copyname.SpecialCells(xlCellTypeVisible).Copy
 startrow.PasteSpecial xlPasteValues
 copypremium.SpecialCells(xlCellTypeVisible).Copy
 startpremium.PasteSpecial xlPasteValuesAndNumberFormats

End If

'X = X + 1

'Loop





Application.ScreenUpdating = True


End Sub

1 个答案:

答案 0 :(得分:2)

记住要记住的事情...执行此操作时要记住大约三件事:

  • 1)您可以在源数据上使用for或for每个循环在行之间移动(在我的示例代码中,迭代的变量为 i
  • 2)您想知道目标表上的最后一行(lrs =最后一行源,lrd =最后一行目标)
  • 3)在源/目标表之间移动时跟踪所有资格(请注意使用src和dst的地方)

记住以上几点的通用代码:

dim src as worksheet, dst as worksheet, i as long, lrs as long, lrd as long
set src = Sheets("SourcE")
set dst = sheets("Destination")
with src
    lrs = .cells(.rows.count,1).end(xlup).row
    for i = 1 to lrs
        if .cells(i,1).value = "what i want it to be" then
            lrd = dst.cells(dst.rows.count,1).end(xlup).row
            dst.rows(lrd+1).value = .rows(i).value
        end if
    next i
end with