0

I'm trying to compare two text cells (like abcDEF) from different sheets. One sheet is fixed but the other is not.

My code is:

Private Sub Worksheet_Change(ByVal Target As Range)

Dim i As Long, LastRow As Long, n As Long
Dim Project As String
Dim Responsible As String, Site As String, Sample As String, _
    Description As String, Parameter As String, Method As String
Dim j As Long

Application.EnableEvents = False

' Find LastRow in Col A into the Sheet2
LastRow = Sheet2.Range("A" & Rows.Count).End(xlUp).Row

' Select all Col A in Project
For Each Value In Sheet2.Range("A2:A" & LastRow)
   Project = Project & "," & Value
Next Value

Sheet1.Range("A2").ClearContents: Sheet1.Range("A2").Validation.Delete

' Create the Data Validation List
With Range("A2").Validation
    .Add Type:=xlValidateList, AlertStyle:=xlValidAlertStop, Operator:=xlBetween,     Formula1:=Project
    .IgnoreBlank = True
    .InCellDropdown = True
    .InputTitle = ""
    .ErrorTitle = ""
    .InputMessage = ""
    .ErrorMessage = ""
    .ShowInput = True
    .ShowError = True
End With

' Select the sheet coinciding with the cell "A2" value
For j = 3 To Sheets.Count

    If Sheets(j).Range("A2").Text = Sheets(1).Range("A2").Text Then
        'Write 4 in sheet1 cell C6 when the two values are coinciding.
        Sheet1.Range("C6") = 4
    End If

Next j
End Sub

The problem is the If... line, probably is the range definition. I've tried .Text and .Value and neither works.

4

2 に答える 2

1

あなたが使いたいかもしれないのは

If StrComp(Sheets(j).Range("A2").Value2, Sheets(1).Range("A2").Value2, _
    vbTextCompare) = 0 Then
'added the underscore since I made it two lines for neatness

vbTextCompare大文字と小文字を区別しませんvbBinaryCompare。大文字と小文字を区別します。文字列の比較については、オンラインで役立つリソースがいくつかあります。

Worksheet_Changeまた、でセルの値を使用および変更していることに気付きましたSheet1。私の推測では、あなたWorksheet_ChangeSheet1ですよね?その場合、 を変更するたびSheet1に、サブルーチンが再度呼び出されます (何度も何度も... クラッシュするまで)。それを防ぐために、追加したい

Application.EnableEvents = False

サブの先頭まで、

Application.EnableEvents = True

最後に。Worksheet_Changeこのようにして、ワークシートに加えた変更はサブをトリガーしません。

于 2012-05-30T14:42:39.690 に答える
0

あなたはEXACT(text1,text2)機能を使うことができます

于 2012-05-30T14:08:33.843 に答える