2017-09-24 22 views
0

Image 列の位置が固定されていないと仮定して、両方の列を自動的に検索してから次のタスクを実行する必要があります。 ケース: -2つの異なる列の値を一意の条件で比較する

カラム 'C'には、カラム 'F'の7桁の値につながる2桁の値があります。 列 'C'には、3桁の値が存在し、列 'F'の8桁の値になります。 '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

私は「sktneer」から得たコードを、stackoverflowユーザーに投稿しました。 –

答えて

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 

、私に知らせてください。

+0

ありがとう!私は列の位置が固定されていないため、ヘッダーに基づいて列を検索するコードを探しています。あなたは私を助けることができますか? –

関連する問題