簡體   English   中英

在Excel中先行再行

[英]Loop through rows then columns in Excel

我在excel中有一系列數據是統一的,A列具有描述,B列具有唯一ID,C列為空白。 然后,接下來的3列具有相同的數據集。 我正在嘗試讓我的vba循環查看兩組數據並比較唯一ID,如果存在差異,它將把它復制到數據范圍中並復制到新的工作表中。

問題在於,不僅有大約200列的6列數據,所以一旦在檢查了第一個數據范圍之后到達了最后一行,則循環需要移到6列以上才能再次開始該過程。

一旦到達最終行,我很難讓循環在6列上移動

Sub finddata()

Dim s As Worksheet
Dim uniqueId As String
Dim finalrow As Long
Dim i As Long
Dim c As Long
Dim rngSearch As Range
Dim rngFound As Range
Dim finalcolumn As Long
Dim offset As Integer

Application.ScreenUpdating = True

uniqueId = Sheets("Data").Range("B2").Value
finalrow = Sheets("Data").Range("G100000").End(xlUp).Row
finalcolumn = Sheets("Data").Range("XFD1").End(xlToLeft).Column
offset = 3

Set s = Sheets("Data")
Set rngSearch = s.Range(s.Cells(2, 5), s.Cells(finalrow, 5))

Sheets("DataValidation").Range("A1:C100000").ClearContents

If i = finalrow GoTo 'guessing this is how to being to loop to move over columns
    For i = 2 To finalrow
        uniqueId = s.Cells(i, 2).Value
        Set rngFound = rngSearch.Find(What:=uniqueId, LookIn:=xlValues, LookAt:=xlWhole)
        If rngFound Is Nothing Then
            s.Range(Cells(i, 1), Cells(i, 6)).Copy
            Sheets("DataValidation").Range("A1048575").End(xlUp).offset(1, 0).PasteSpecial xlPasteFormulasAndNumberFormats
            End If
    Next i

MsgBox "Done"
End Sub

試試那個

For j = 1 to finalcolumn step 6
    Set rngSearch = s.Range(s.Cells(2, j - 1 + 5), s.Cells(finalrow, j - 1 + 5))
    For i = 2 To finalrow
        uniqueId = s.Cells(i, 2 + j - 1).Value
        Set rngFound = rngSearch.Find(What:=uniqueId, LookIn:=xlValues, LookAt:=xlWhole)
            If rngFound Is Nothing Then
                s.Range(Cells(i, 1 + j - 1), Cells(i, 6 + j - 1)).Copy
                Sheets("DataValidation").Range("A1048575").End(xlUp). _
                               offset(1, 0).PasteSpecial xlPasteFormulasAndNumberFormats
            End If
    Next i
Next j

希望能幫助到你

這是一個簡短的示例,說明如何在3列的統一范圍內進行迭代,並向右偏移6個偏移量。您說您的范圍是統一的,因此我對rngSet的初始值進行了硬編碼。

在“每個我都在”中打印單元格的地址,但是您可以在此處進行檢查。 While循環到達空單元格時將結束。

Dim rngSet As Range, rngRow As Range

Set rngSet = Range("A1:B6")

While Not IsEmpty(rngSet.Cells(1, 1).Value)

    For Each rngRow In rngSet.Rows
        Debug.Print rngRow.Cells(1, 1).Address
    Next rngRow

    Set rngSet = rngSet.Offset(0, 6)
Wend

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM