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_Change是为了Sheet1,是吗?如果是这种情况,那么每次您修改Sheet1时,都会再次调用 sub(一次又一次......直到它崩溃)。为了防止这种情况,您要添加

Application.EnableEvents = False

到子的开头,然后

Application.EnableEvents = True

在最后。这样,您对工作表所做的任何更改都不会触发Worksheet_Change子。

于 2012-05-30T14:42:39.690 回答
0

你可以使用EXACT(text1,text2)功能

于 2012-05-30T14:08:33.843 回答