How to compare columns from two different excel workbooks

后端 未结 2 996
伪装坚强ぢ
伪装坚强ぢ 2020-12-22 06:51

I have an Excel-Workbook which has two sheets \'Task\' and \'Cities\'. I need to compare the code for validation of records from \'Task\' sheet with that one in \'Cities\' S

相关标签:
2条回答
  • 2020-12-22 07:22

    I have prepared another workbook with name 'Sample_Data.xlsx' under which I will have a sheet 'cities'.

    So where else in the below code I have to make changes to work it correctly; when my 'Sample_Data.xlsx' workbook is closed. The below code opens the workbook; but do not do validation.

    Dim CityString As String
    Dim CityArray() As String
    
    'Get the last row
    'Dim lastRow As Integer
    LastRow = Sheets("Task").UsedRange.Rows.Count
    
    Dim wrk As Workbook
    Set wrk = Workbooks.Open("E:\Final\Sample_Data.xlsx")
    
    nLastRowSheet2 = wrk.Worksheets("cities").UsedRange.Rows.Count
    
    Dim c As Range
    Dim d As Range
    Dim e As Variant
    
    'Turn screen updating off to speed up macro code.
    'User won't be able to see what the macro is doing, but it will run faster.
    Application.ScreenUpdating = False
    
    For Each c In Worksheets("Task").Range("A2:A" & LastRow)
        CityString = c
        CityArray() = Split(CityString, ";")
        For Each e In CityArray()
            e = Trim(e)
    
            Dim rngFnder As Range
            On Error Resume Next
    
            Set rngFnder = wrk.Sheets("Cities").Range("A2:A" & nLastRowSheet2).Find(e)
    
            If rngFnder Is Nothing Then
                c.Interior.Color = vbRed
            End If
    
            On Error GoTo 0
        Next
    Next
    
    0 讨论(0)
  • 2020-12-22 07:40

    When you say "on two different excelssheets" I'm guessing you mean they are in a different Excel workbook file?

    When you use the following line you are refering to the sheet "Task" in the active workbook.

    Worksheets("Task").Range("A2:A" & LastRow)
    

    You should specify the workbook to avoid writing to the wrong one. Using thisWorkbook refers to the workbook with the code e.g.

    ThisWorkbook.Worksheets("Task").Range("A2:A" & LastRow)
    

    To access any open workbook including the current workbook use

    Workbooks("example.xls").Worksheets("Task").Range("A2:A" & LastRow)
    

    If the workbook is closed you can open it using

    dim wrk as Workbook
    set wrk = Workbooks.Open("C:\Docs\example.xls") 
    wrk.Worksheets("Task").Range("A2:A" & LastRow)
    

    If you want to know more about workbooks in VBA you can read about them here

    0 讨论(0)
提交回复
热议问题