我正在构建一个程序,该程序可以衡量我们公司的行为和进度的度量标准,而我在特定部分上遇到了麻烦。我正在VBA中执行此操作,我想执行以下操作:
1. Compare a range on two spreadsheets to find mismatches.
2. Calculate (not format) how many cells are different and then send that
resultant value a target cell on another spreadsheet in the workbook.
EX: If 2 out of 10 cells do not match then the target cell
value should be 2
3. Replicate this process for about 6 other parameters in the workbook
(That is the easy part I think).
我已经使用/提供了以下VBA函数来尝试得出结果: WorksheetFunction.sum 评估(SumProduct)
我不认为问题出在比较代码本身(正如我刚刚借用的一些互联网示例所见。)但是在'Else'语句之后出现的函数中。代码可以正常运行和调试,但是不会产生任何答案。下面的代码假设已声明变量(出于空间目的)。
Worksheets("Generalized Report").Activate
strRangeToCheck = "F2:F10000" 'Range can change depending on amount of data on sheets'
varSheetA = Worksheets("Contract").Range(strRangeToCheck)
varSheetB = Worksheets("As Built").Range(strRangeToCheck)
'Loop thru and do the comparison cell by cell via an array
For iRow = LBound(varSheetA, 1) To UBound(varSheetA, 1)
For iCol = LBound(varSheetA, 2) To UBound(varSheetA, 2)
If varSheetA(iRow, iCol) = varSheetB(iRow, iCol) Then
' Cells are identical.
' Do nothing.
Else
' Cells are different.
' Calculate how many cells are different
Worksheet("Generalized Report").Activate
Worksheet("Generalized Report").Range("A8") = Evaluate("=SUMPRODUCT(--('Contract'!F2:F10000<>'As Built'!F2:F10000)")
在这种特殊情况下,我期望值为0(因为这是测试数据),但是该值应等于不同单元格的数量。根据我的调整,我的代码会发生以下三件事:
#Value!
错误感谢您的时间。
答案 0 :(得分:0)
我会计算VBA中的差异,而不是尝试使用SUMPRODUCT公式:
Dim DifferenceCount as Long
Worksheets("Generalized Report").Activate
strRangeToCheck = "F2:F10000" 'Range can change depending on amount of data on sheets'
varSheetA = Worksheets("Contract").Range(strRangeToCheck)
varSheetB = Worksheets("As Built").Range(strRangeToCheck)
'Loop thru and do the comparison cell by cell via an array
For iRow = LBound(varSheetA, 1) To UBound(varSheetA, 1)
For iCol = LBound(varSheetA, 2) To UBound(varSheetA, 2)
If varSheetA(iRow, iCol) = varSheetB(iRow, iCol) Then
' Cells are identical.
' Do nothing.
Else
' Cells are different.
DifferenceCount = DifferenceCount + 1
End If
Next iCol
Next iRow
Worksheet("Generalized Report").Range("A8") = DifferenceCount
修改
考虑到这一点,还有另外两种使用您的公式的选择...
首先,您的整个宏可能只是
Worksheet("Generalized Report").Range("A8") = Evaluate("=SUMPRODUCT(--('Contract'!F2:F10000<>'As Built'!F2:F10000)")
这会将公式结果放入A8。
第二种选择是直接在A8中使用公式=SUMPRODUCT(--('Contract'!F2:F10000<>'As Built'!F2:F10000)
。
如果您有多个不匹配的单元格,则问题中的代码将在两个循环中多次评估公式。这是不必要的,对于大型/复杂的电子表格可能会非常慢。