2015-02-09 74 views
1

背景:使用VBA在同一工作簿的工作表之間搜索值

我有一個帶有兩個工作表(即「工作表1」和「工作表2」)的excel文件。兩張紙都有相同的標題。

Sheet1-header從columnB和Sheet2-從columnA開始。

第一個標題(在兩張表中)都是唯一的標識。

無論是在各個片的列具有值

的陣列

問題:

如何搜索如果Sheet 2中(columnA)的值是本Sheet 1中使用VBA(columnB)..?

我theoritical程序:

循環直到UID在 '工作表Sheet1' 爲空

  1. 轉到 'Sheet2的'
  2. 讀UID值
  3. 去 '工作表Sheet1'
  4. 搜索在UID列中進行讀取UID
  5. 如果找到

5.1的一些操作

  • 如果沒有找到
  • 6.1的一些操作

    循環結束

    請指導我我怎麼能做到這一點搜索活動。

    提前致謝!

    回答

    0

    您可以使用字典來做到這一點。使用字典意味着您只讀取sheet1中的值,而不是讀取sheet2中的每個值。

    Sub CompareColumns() 
    
        Dim dict As Object 
        Set dict = CreateObject("Scripting.dictionary") 
    
        Dim sheet1 As Worksheet, Sheet2 As Worksheet 
        Set sheet1 = ThisWorkbook.Worksheets("Sheet1") 
        Set Sheet2 = ThisWorkbook.Worksheets("Sheet2") 
    
        ' Read values from sheet1 to dictionary 
        Dim lastRow As Long 
        lastRow = sheet1.Cells(sheet1.Rows.Count, 1).End(xlUp).Row 
        Dim i As Long 
        For i = 1 To lastRow 
         ' Store value to dictionary 
         dict(sheet1.Cells(i, 1).Value) = 1 
        Next 
    
        ' Read from sheet2 and check if each value exists 
        lastRow = Sheet2.Cells(Sheet2.Rows.Count, 2).End(xlUp).Row 
        For i = 1 To lastRow 
         ' Check if value exists in dictionary 
         If dict.exists(Sheet2.Cells(i, 2).Value) Then 
          ' found 
         Else 
          ' not found 
         End If 
        Next 
    
    End Sub 
    
    0

    你可以像這樣開始:

    Sub Test() 
        Dim AlastRow As Integer 
        Dim Blastrow As Integer 
    
        With ThisWorkbook.Worksheets("Sheet1") 
         Blastrow = .Cells(.Rows.Count, "B").End(xlUp).Row 
        End With 
    
        With ThisWorkbook.Worksheets("Sheet2") 
         AlastRow = .Cells(.Rows.Count, "A").End(xlUp).Row 
        End With 
    
        Dim ra As Range 
        Dim rb As Range 
    
        With ThisWorkbook 
         Set ra = .Worksheets("Sheet1").Range("A1", "A" & AlastRow) 
         Set rb = .Worksheets("Sheet2").Range("B1", "A" & AlastRow) 
        End With 
    
        For Each cellb In rb.Cells 
         For Each cella In ra.Cells 
          If cella.Value = cellb.Value Then 
           'Found match, do stuff 
          Else 
           'Did not found match do stuff too 
          End If 
         Next 
        Next 
    End Sub 
    
    相關問題