循环通过2列的范围

时间:2013-05-08 19:53:26

标签: excel vba excel-vba

我的问题一再被回答,但我不理解这些解决方案,因此无法根据我的需要对其进行定制。

这是指向StackOverflow Loop through each row of a range in Excel上的解决方案的链接。

Dim rng As Range
Dim row As Range
Dim cell As Range

Set rng = Range("A2:b22")

For Each row In rng.Rows
  For Each cell in row.Cells
    'Do Something
MsgBox cell
  Next cell
Next row

这是我应该进入循环的代码。它应该取第一列的值,复制数据,然后取第二列的值并粘贴数据。

它正在做的是使用第1列中的相同值。那么CELL的价值在什么时候从A2变为B2?

Windows("UnitedOrig.xlsx").Activate
Sheets(CurYearTxtPRAC).Select
Range("A4:U4").Select

ColumnFROM = MyColumnLetter(Cells.Find(What:=cell, After:=ActiveCell,  
    LookIn:=xlFormulas, LookAt:=xlPart, SearchOrder:=xlByRows,  
    SearchDirection:=xlNext, MatchCase:=False, SearchFormat:=False).Column)

Range(ColumnFROM & "5:" & ColumnFROM & LastRowPRAC).Select
Selection.Copy

Windows("United.xlsx").Activate
Sheets("PRACS").Select
Range("A1:U1").Select

ColumnTO = MyColumnLetter(Cells.Find(What:=cell, After:=ActiveCell, 
    LookIn:=xlFormulas, LookAt:=xlPart, SearchOrder:=xlByRows, 
    SearchDirection:=xlNext, MatchCase:=False, SearchFormat:=False).Column)

2 个答案:

答案 0 :(得分:3)

为了理解循环正在做什么,您需要监视正在处理的内容。您可以通过更改单元格的颜色或向行添加边框来轻松完成此操作。

将这两个潜艇粘贴到模块中:

Sub WhereInDoubleLoop()
    Dim rng As Range
    Dim row As Range
    Dim cell As Range

    Set rng = Range("A1:D5")

    For Each row In rng.Rows
    ' Do something to the row
    row.BorderAround xlContinuous, xlThin, vbBlack
      For Each cell In row.Cells
        ' Do something to the cell
        cell.Interior.Color = vbYellow
      Next cell
    Next row
End Sub

Sub WhereInSingleLoop()
    Dim rng As Range
    Dim cell As Range

    Set rng = Range("A1:D5")

    For Each cell In rng
        ' Do something to the cell
        cell.Interior.Color = vbGreen
    Next cell
End Sub

逐步完成每个循环(代码编辑器中的F8),您应该更好地了解正在发生的事情。一旦理解了它们,就可以为自己的循环修改它们。

答案 1 :(得分:1)

我最近做了类似的事情(我实际上对两个不同表格上的多个单元格进行了比较)并且是VBA的新手,但是我没有使用范围而是根据特定的行/列数来设置循环,而我发现你没有需要。激活读取或写入或更改单元格(以下方法我使用而不是.Select / .Activate使运行时间大约快300-400%)。这里有一些非常快速的伪代码,希望它们有意义并且应该可以根据需要轻松修改。

Dim oSheet As Excel.Worksheet, vSheet As Excel.Worksheet
Dim oRowCount As Integer, vRowCount As Integer
Dim oRow, vRow
Dim someDataToCopy As String

'Gets last row # for oSheet & vSheet    
oRowCount = oSheet.Cells.SpecialCells(xlLastCell).row
vRowCount = vSheet.Cells.SpecialCells(xlLastCell).row

For oRow = 2 to oRowCount
    someDataToCopy = oSheet.Cells(oRow, 4).Value 'Where 4 is an arbitrary column
    For vRow = 2 to vRowCount
        vSheet.Cells(vRow, 8).Value = someDataToCopy 'Where 8 is an arbitrary column
    Next vRow
Next oRow

如果您不是每行复制一个单元格,而是每行复制多个单元格以及添加更多“= oSheet.Cells(oRow,x)”,您可以添加更多“临时”数据对象(例如someDataToCopy2)来对应.Value“根据需要。如果您对代码的作用有任何疑问,请与我们联系!

相关问题