检查值是否已存在于不同工作表中并创建混合它们的结果表

时间:2016-08-18 06:50:20

标签: excel vba excel-vba

我需要一个适用于不同表格的宏(让我们称之为x y和z):

  x
------------
a 0 
b 1  
c 2  

  y
------------
a 3 
b 1  
c 2 

  z
------------
a 3 
b 1  
c 0 

我需要一个像这样的结果表(表格已经制作,只需填写):

  x  y  z
------------
a 0  1  2
b 3  1  2
c 3  1  0

我需要什么?扫描表时," a b和c"将重复。我需要打印每个结果而不在该列中创建额外的数据集。

我不想要

  x  y  z
------------
a 0    
b 1 
c 2     
a    3  
b    1  
c    2  
a       3
b       1
c       0

我怎样才能做到这一点?

要在正确的行中指定值,我将此循环作为当前行的控件:

Sub LoopRange()

Dim rCell As Range
Dim rRng As Range

Set rRng = Hoja1.Range("B17:B30")

For Each rCell In rRng.Cells
    Debug.Print rCell.Address, rCell.Value
    'MsgBox rCell.row'

Next rCell

End Sub

如何提取(a,b和c)的te值,以便将字符串与结果表进行比较?

最终的excel结构应该是这样的:

Excel estructure

1 个答案:

答案 0 :(得分:1)

这看起来对我有用。如果您逐步使用调试器,您将能够看到它正在做什么并修改它,以防我做出一些不正确的假设。

我从名为Hoja1的工作表中提取数据。我写了一个名为xyz_result的工作表。我假设x,y和z列标题已经在B1:D1中已经存在。我还假设a,b,c行名称在A2:A4

中存在
Sub LoopRange()

    Dim rCell As Range
    Dim rRng As Range
    Dim rRng2 As Range

    Dim Wbk As Workbook

    Set Wbk = ActiveWorkbook


    Worksheets("Hoja1").Activate
    Dim currentTable As String
    Dim abcValue As String
    Dim currentValue As String

    Dim rowNum As Integer
    Dim colNum As Integer



    'Set rngMyRange = .Range(.Range("a1"), .Range("A65536").End(xlUp))
    Set rRng = Range("B17:B30")

    For Each rCell In rRng.Cells

        If Len(Trim(rCell.Offset(0, -1).Value)) = 0 Then  ' It might be to the left of text such as x, y, or z
            If Len(Trim(rCell.Value)) > 0 Then ' It is text such as x, y, or z
                currentTable = rCell.Value
            End If
        End If

        If Len(Trim(rCell.Offset(0, -1).Value)) > 0 Then 
            abcValue = rCell.Offset(0, -1).Value
            currentValue = rCell.Value
        End If


        If Len(currentTable) > 0 And Len(abcValue) > 0 Then
            Worksheets("xyz_Result").Activate
            Set c = Range("A1:D4").Find(abcValue, LookIn:=xlValues)
            rowNum = c.row
            Set r = Range("A1:D4").Find(currentTable, LookIn:=xlValues)
            colNum = r.Column
            Cells(rowNum, colNum).Value = currentValue
        End If

        Worksheets("Hoja1").Activate


    Next rCell

 End Sub

enter image description here