Image 假设列位置不固定首先必须自动搜索两列,然后执行以下任务。 情况: -
在专栏C' C'存在两位数值,在“F&F”列中产生七位数值。 在专栏C' C'存在三位数值,这导致列F'中的八位数值。 我想验证是否' F2'和' F3'从21开始,如果此行中没有Msgbox'错误'。以及是否' F6'和' F7'以和228开头,如果此行没有Msgbox'错误'。
感谢。 ++代码
Sub CompareColumns()
Dim lr As Long, n As Long
Dim rng As Range, cell As Range
Dim strA As String, strB As String, str As String
Dim NotMatched As Boolean
lr = Cells(Rows.Count, 1).End(xlUp).Row
'Assuming your data starts from Row2
Set rng = Range("B2:B" & lr)
str = "The following cells don't match." & vbNewLine & vbNewLine
For Each cell In rng
If cell <> "" Then
n = Len(cell.Offset(0, -1))
If n > 0 Then
strA = cell.Offset(0, -1).Text
strB = Left(cell, n)
If strA <> strB Then
NotMatched = True
str = str & cell.Offset(0, -1).Address(0, 0) & " : " &
cell.Offset(0, -1).Value & vbTab & cell.Address(0, 0) & " : " & cell.Value &
vbNewLine
End If
Else
str = str & cell.Offset(0, -1).Address(0, 0) & " : " & cell.Offset(0, -1).Value & vbTab & cell.Address(0, 0) & " : " & cell.Value & vbNewLine
End If
End If
n = 0
strA = ""
strB = ""
Next cell
If NotMatched
MsgBox str, vbInformation
Else
MsgBox "Both columns match.", vbInformation
End If
End Sub
答案 0 :(得分:0)
您提供的代码比较A列和B列,而不是C和F.代码比较A列每行的值是否与B列中值的起始位数相同,然后打印出所有不同的值行。
代码有一些小错误,我修改如下:
Sub CompareColumns()
Dim lr As Long, n As Long
Dim rng As Range, cell As Range
Dim strA As String, strB As String, str As String
Dim NotMatched As Boolean
lr = Cells(Rows.Count, 1).End(xlUp).Row
'Assuming your data starts from Row2
Set rng = Range("B2:B" & lr)
str = "The following cells don't match." & vbNewLine & vbNewLine
For Each cell In rng
If cell <> "" Then
n = Len(cell.Offset(0, -1))
If n > 0 Then
strA = cell.Offset(0, -1).Text
strB = Left(cell, n)
If strA <> strB Then
NotMatched = True
str = str & cell.Offset(0, -1).Address(0, 0) & " : " & cell.Offset(0, -1).Value & vbTab & cell.Address(0, 0) & " : " & cell.Value & vbNewLine
End If
Else
str = str & cell.Offset(0, -1).Address(0, 0) & " : " & cell.Offset(0, -1).Value & vbTab & cell.Address(0, 0) & " : " & cell.Value & vbNewLine
End If
End If
n = 0
strA = ""
strB = ""
Next cell
If NotMatched Then
MsgBox str, vbInformation
Else
MsgBox "Both columns match.", vbInformation
End If
End Sub
如果这不是您想要的,请告诉我。