我有一个基于宏的Excel文件,可生成收到的项目列表及其状态(即接收,修复等)。这个程序每天运行,现在我将它捕获前一天的列表并将其放在名为PreviousData的电子表格中,然后使用当前日期列表进行更新,该列表放在名为Data的电子表格中;这用于比较我们认为我们在前一天修复/更改状态的内容。
我基本上是在VBA自学,所以我不是超级高效或经验丰富。我想做的是以下几点:
在数据电子表格中,抓住从J2开始的订单号
切换到PreviousData电子表格,并从步骤1中搜索订单号
场景A:如果在PreviousData上找到订单号,请比较两张纸上订单号旁边的状态值;如果它们不同,运行一些代码,否则什么都不做
场景B:如果在PreviousData上找不到订单号,则不执行任何操作
我做了一些搜索互联网并找到了一些东西(实际上可能来自这个论坛),它会逐行排列并比较单元格值,但是如果出现方案B,那么函数将失败,并且#34;超出范围。"这是我尝试过的代码,经过修改后试图开始工作:
Sub output()
Dim varSheetA As Variant
Dim varSheetB As Variant
Dim varSheetRMA As Variant
Dim strRangeToCheck As String
Dim strRangeRMA As String
Dim Variable As String
Dim iRow As Long
Dim iCol As Long
Dim Count As Integer
strRangeToCheck = "K2:L1000"
strRangeRMA = "J2:J1000"
' If you know the data will only be in a smaller range, reduce the size of the ranges above.
Debug.Print Now
varSheetA = Worksheets("PreviousData").Range(strRangeToCheck)
varSheetB = Worksheets("Data").Range(strRangeToCheck) ' or whatever your other sheet is.
varSheetRMA = Worksheets("Data").Range(strRangeRMA)
Debug.Print Now
Sheets("Data").Select
Range("J2").Select
Selection.Copy
Sheets("PreviousData").Select
Cells.Find(What:=Variable, After:=ActiveCell, LookIn:=xlFormulas, _
LookAt:=xlPart, SearchOrder:=xlByRows, SearchDirection:=xlNext, _
MatchCase:=False, SearchFormat:=False).Activate
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.
' Code goes here for whatever it is you want to do.
End If
Next iCol
Next iRow
End Sub
请帮助:)
答案 0 :(得分:3)
此代码应该更容易理解+它可以完成工作。
Option Explicit
Sub CompareStatuses()
Dim ws1 As Worksheet, ws2 As Worksheet, rng1 As Range, rng2 As Range
Dim lr1&, lr2&, i&, j&
Set ws1 = ThisWorkbook.Sheets("Data")
Set ws2 = ThisWorkbook.Sheets("PreviousData")
lr1 = ws1.Range("J" & Rows.Count).End(xlUp).Row
lr2 = ws2.Range("J" & Rows.Count).End(xlUp).Row
For i = 2 To lr1
For j = 2 To lr2
Set rng1 = ws1.Range("J" & i)
Set rng2 = ws2.Range("J" & j)
If StrComp(CStr(rng1.Value), CStr(rng2.Value), vbTextCompare) = 0 And _
StrComp(CStr(rng1.Offset(0, 1).Value), CStr(rng2.Offset(0, 1).Value) _
,vbTextCompare) <> 0 Then
' found a matching Order + both statuses are different
' this is where you wanted to run some code
End If
Set rng1 = Nothing
Set rng2 = Nothing
Next j
Next i
End Sub