[英]Excel VBA: How to compare values of two cells?
我正在嘗試比較連續行的兩列中的值。 具體來說,我想檢查每一行的 B 列和 C 列下的值,並直接在其上方。 如果匹配,則執行一些 XYZ 操作。
我有下面的代碼,我嘗試使用它,但它不斷拋出錯誤。
編輯:我在下面提供了一個更改后的代碼,它沒有我以前的任何錯別字。 我仍然面臨同樣的問題。
Sub MergeDupes2()
'Declaring variables
Dim ws As Worksheet
Dim lngRow As Integer
Dim columnToMatch As Integer: columnToMatch = 2
Dim column2ToMatch As Integer: column2ToMatch = 3
'Setting current worksheet
Set ws = ThisWorkbook.Sheets("Sheet1")
'Finding and calling the last row
lngRow = Range("A" & Rows.Count).End(xlUp).Row
'Starting Loop
Do
'Finding Matching Values
If Range("C" & lngRow).Value = Range("C" & lngRow - 1).Value And Range("B" & lngRow).Value = Range("B" & lngRow - 1).Value Then
For i = 4 To 50
If ws.Cells(lngRow - 1, i).Value = "" Then
ws.Cells(lngRow - 1, i).Value = ws.Cells(lngRow, i).Value
End If
Next i
End If
lngRow = lngRow - 1
Loop Until lngRow = 2
End Sub
這包含了以下一些建議。 然而,我在這條線上仍然有一個錯誤。 我有它的兩個版本,但似乎都不起作用。
If ws.Cells(lngRow, columnToMatch).Value = ws.Cells(lngRow - 1, columnToMatch).Value And ws.Cells(lngRow, column2ToMatch).Value = ws.Cells(lngRow - 1, column2ToMatch).Value Then
If Range("C" & lngRow).Value = Range("C" & lngRow - 1).Value And Range("B" & lngRow).Value = Range("B" & lngRow - 1).Value Then
在沒有完全理解您的意圖的情況下,這里有一些可能會有所幫助的修復方法:
Set ws = ThisWorkbook("Sheet1")
更改為Set ws = Worksheets("Sheet1")
Set lngRow = ...
更改為lngRow = ...
ws.
在Cells(...
當您比較單元格值時所以完整的代碼看起來像這樣:
Sub SortAndMergeDupes()
Dim lngRow As Long
Dim ws As Worksheet
Dim columnToMatch As Integer: columnToMatch = 2
Dim column2ToMatch As Integer: column2ToMatch = 3
Set ws = Worksheets("Sheet1")
With ActiveSheet
lngRow = .Cells(65536, columnToMatch).End(xlUp).Row
Do
If ws.Cells(lngRow, columnToMatch).Value = ws.Cells(lngRow - 1, columnToMatch).Value And ws.Cells(lngRow, column2ToMatch).Value = ws.Cells(lngRow - 1, column2ToMatch).Value Then
For i = 4 To 50
If .Cells(lngRow - 1, i).Value = "" Then
.Cells(lngRow - 1, i).Value = .Cells(lngRow, i).Value
End If
Next i
.Rows(lngRow).Delete
End If
lngRow = lngRow - 1
Loop Until lngRow = 1
End With
End Sub
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.