Comparing two text cells in different sheets

允我心安 提交于 2019-12-13 04:40:38

问题


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.


回答1:


What you may want to use is

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 is case-insensitive, vbBinaryCompare is case-sensitive. There are several resources online about string comparison that can help you.

Also, I noticed you're using Worksheet_Change and changing the value of a cell on Sheet1. My guess is that your Worksheet_Change is for Sheet1, yes? If that's the case, then every time you modify Sheet1, the sub gets called again (and again and again... until it crashes). To prevent that, you want to add

Application.EnableEvents = False

to the start of the sub, then

Application.EnableEvents = True

at the end. This way any changes you make to the worksheet won't trigger the Worksheet_Change sub.




回答2:


you can use EXACT(text1,text2) function



来源:https://stackoverflow.com/questions/10817799/comparing-two-text-cells-in-different-sheets

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!