[英]excel vba DO UNTIL and IF, to compare string cells
子比較()
j = 0
For i = 0 To 1109
Do Until Cells(2 + i, 3) = Cells(2 + j, 12)
i = i + 1
Loop
If Cells(2 + i, 4) = Cells(2 + j, 13) Then
Cells(2 + j, 16) = "OK"
End If
i = 0
j = j + 1
Next i
End Sub
如果列D
和M
中的單元格相同(使用If
指令),而僅當列C
和L
中的相關名稱相同(使用Do Until
指令)時,我想寫一個“ OK”。 所以我想做一個比較。
但是單元格中的名稱(在Do Until
循環”內部)由一串字組成。 Excel給我一個與DO UNTIL
句子有關的錯誤。
你可以幫幫我嗎?
以下是一些示例數據:
這是我最后要在這里輸入圖片描述的內容
對於相同的細胞名稱(A和J列),對於找到的每個匹配項,查看條件1的值(B和K列),最后將其寫在P列中(箭頭等於模型2中的匹配項之一)或OK(如果cond1的值相同)或NO(如果od cond1的值不同)
我不確定您是否要逐行比較D
/ M
和C
/ L
或者您是否真的要比較所有行。 因此,我針對兩種情況調整了您的代碼:
Option Explicit
Sub ComparisonRowByRow()
Dim i As Long
With ThisWorkbook.Worksheets("Sheet1")
For i = 0 To 1109
If .Cells(2 + i, 3).Value2 = .Cells(2 + i, 12).Value2 And _
.Cells(2 + i, 4).Value2 = .Cells(2 + i, 13).Value2 Then
.Cells(2 + i, 16).Value2 = "OK"
End If
Next i
End With
End Sub
Sub CompareAllWithAll()
Dim i As Long, j As Long
Dim lngLastRow As Long
With Application
.EnableEvents = False
.Calculation = xlCalculationManual
.ScreenUpdating = False
End With
With ThisWorkbook.Worksheets("Sheet1")
lngLastRow = .Cells.Find("*", SearchDirection:=xlPrevious, SearchOrder:=xlByRows).Row
For i = 0 To 1109
.Cells(2 + i, 16).ClearContents
For j = 2 To lngLastRow
If .Cells(2 + i, 3).Value2 = .Cells(2 + j, 12).Value2 And _
.Cells(2 + i, 4).Value2 = .Cells(2 + j, 13).Value2 Then
If .Cells(2 + i, 16).Value2 = vbNullString Then
.Cells(2 + i, 16).Value2 = "OK, match found in row " & j
Else
.Cells(2 + i, 16).Value2 = .Cells(2 + i, 16).Value2 & ", " & j
End If
End If
Next j
Next i
End With
With Application
.Calculation = xlCalculationAutomatic
.ScreenUpdating = True
.EnableEvents = True
End With
End Sub
如果您真的希望將所有行與所有行進行比較,那么找到匹配的行也很重要。 因此,我將其添加到代碼中以記錄匹配。
請記住,第二sub
非常耗時。 如果您有1,109行,那么代碼將運行1,109 * 1,109次。 這相當於進行了超過120萬次迭代:將D2與M2,M3,M4,M5,... M1109進行比較,將D3與M2,M3,M4,M5,M6,... M1109等進行比較。
為了使此過程更快,我關閉了ScreenUpdating
, Events
和Calculation
。 但是, arrays
有更好/更快的方法。 但是我不確定您是否熟悉數組,因此我保留了原始代碼。 畢竟,我們正在努力幫助你和你的代碼(你將不得不更新,並在未來保持)。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.