使代码动态化

时间:2016-01-13 23:09:03

标签: excel vba excel-vba dynamic

我想比较两本工作簿。工作簿列出了许多项目ID项目,项目名称,完成日期,人员分配项目等...工作簿一直在更新,所以每周一次,我会查找任何更改。我希望能够轻松找到变化。工作簿有21列,行数随项目完成或添加到工作计划中而变化。我发现以下代码突出显示了最新版本工作簿的差异。但是,如何使以下代码动态化?如果我的工作簿上有删除或添加,则会突出显示整个工作表。

Option Explicit
Sub compare2sheetsex() 'and highlight the diffrence
    Dim wb1 As Workbook, wb2 As Workbook, sh1 As Worksheet, sh2 As Worksheet
    Dim rCount As Long, cCount As Long
    Set wb1 = Workbooks(InputBox("enter b1"))
    Set wb2 = Workbooks(InputBox("enter b2"))
    Set sh1 = wb1.Sheets(InputBox("enter s1"))
    Set sh2 = wb2.Sheets(InputBox("enter s2"))
    rCount = sh1.UsedRange.Rows.Count
    cCount = sh1.UsedRange.Columns.Count
    Dim r As Long, c As Integer
    For r = 1 To rCount
        For c = 1 To cCount
            If sh1.Cells(r, c) <> sh2.Cells(r, c) Then
                sh2.Cells(r, c).Interior.ColorIndex = 6
            End If
        Next c
    Next r
    Set sh1 = Nothing
    Set sh2 = Nothing
End Sub

0 个答案:

没有答案