如何在不同的工作表中查找一个工作表中的行?

时间:2014-01-08 21:44:01

标签: excel excel-vba vba

我主要想找到工作簿A中的单元格在工作簿B中的位置。工作簿B中每个工作表的单元格都是红色的,因此找到的单元格应该变为未填充(如此代码底部所示)。问题在于我的第二个for循环,我不太确定如何使用工作簿A中复制的单元格搜索工作簿B,或者是否有更有效的方法来执行此操作。

Sub Macro7()
Dim jcolumn As Range
wsht = InputBox("Enter Name of bucket: ")
Workbooks("A").Worksheets(wsht).Activate
    For Each cell In Columns("J:J")
        cell.Copy
        Workbooks("B").Worksheets(wsht).Activate
        Columns("J:J").Select
        For Each icell In Columns("J:J")
                jcolumn.Find(cell).Select
                With Selection.Interior
                .Pattern = xlNone
                .TintAndShade = 0
                .PatternTintAndShade = 0
                End With
        Next
    Next

End Sub

1 个答案:

答案 0 :(得分:0)

这就是我要这样做的方式:

Sub YourRoutine()

Application.ScreenUpdating = False

Dim wb1 As Workbook, wb2 As Workbook
Dim ws1 As Worksheet, ws2 As Worksheet
Dim myFileName As String

myFileName = "C:\Users\Bernard\Desktop\test.xlsx" 'Put your full extension & filename here


Set wb1 = ThisWorkbook
Set ws1 = ActiveSheet
Set wb2 = Workbooks.Open(myFileName)
Set ws2 = wb2.ActiveSheet

'Set-up your parameters
yourCol1 = 1 'Change 1 to the column in which your data is located in "ws1"
yourCol2 = 1 'Change 1 to the column in which your data is located in "ws1"
firstWs1 = 1 'Change 1 to the row in which the first data is located in "ws1"
firstWs2 = 1 'Change 1 to the row in which the first data is located in "ws2"

'Locate last row of ws1
wb1.Activate
ws1.Activate
lastWs1 = Cells(Rows.Count, yourCol1).End(xlUp).Row

'Locate last row of ws2
wb2.Activate
ws2.Activate
lastWs2 = Cells(Rows.Count, yourCol2).End(xlUp).Row

'Loop through all the rows of ws1
For x = firstWs1 To lastWs1 
    wb1.Activate
    myData1 = Cells(x, yourCol1)

    'Loop through all the rows of ws2
    For y = firstWs2 To lastWs2
        wb2.Activate
        myData2 = Cells(y, yourCol2)

        If myData1 = myData2 Then

            Cells(y, yourCol2).Interior.Color = xlColorIndexNone

        End If

    Next y

Next x

Application.ScreenUpdating = True

End Sub

编辑:编辑了我的代码,因为它没有经过测试,也没有工作。现在它已经过测试和运作。