Compare two excel sheets

前端 未结 4 1850
悲哀的现实
悲哀的现实 2020-12-16 08:20

How do I compare two excel sheet and determine which column is missing?

(I would like to compare a list of countries from sheet A with sheet B, then mark which count

4条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-12-16 08:46

    You can use ADO with Excel

    Dim cn As Object
    Dim rs As Object
    Dim strFile As String
    Dim strCon As String
    Dim strSQL As String
    Dim s As String
    Dim i As Integer, j As Integer
    
    ''This is not the best way to refer to the workbook
    ''you want, but it is very conveient for notes
    ''It is probably best to use the name of the workbook.
    
    strFile = ActiveWorkbook.FullName
    
    ''Note that if HDR=No, F1,F2 etc are used for column names,
    ''if HDR=Yes, the names in the first row of the range
    ''can be used. 
    ''This is the Jet 4 connection string, you can get more
    ''here : http://www.connectionstrings.com/excel
    
    strCon = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" & strFile _
        & ";Extended Properties=""Excel 8.0;HDR=Yes;IMEX=1"";"
    
    ''Late binding, so no reference is needed
    
    Set cn = CreateObject("ADODB.Connection")
    Set rs = CreateObject("ADODB.Recordset")
    
    
    cn.Open strCon
    
     ''Query example:
     strSQL = "SELECT Country " _
           & "FROM [Sheet1$] a " _
           & "WHERE Country NOT IN " _
           & "SELECT Country FROM [Sheet2$]"
    
    
    ''Open the recordset for more processing
    ''Cursor Type: 3, adOpenStatic
    ''Lock Type: 3, adLockOptimistic
    ''Not everything can be done with every cirsor type and 
    ''lock type. See http://www.w3schools.com/ado/met_rs_open.asp
    
    rs.Open strSQL, cn, 3, 3
    
    If rs.Count>0 Then
        MsgBox rs.GetString
    End If
    

    It is also possible to quickly write the recordset to a sheet with CopyFromRecordset.

提交回复
热议问题