我正在尝试比较来自不同工作表的两个文本单元格(如abcDEF
)。一张是固定的,另一张则没有。
我的代码是:
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
问题是If...
行,可能是范围定义。我尝试了.Text
和.Value
,但都没有效果。
答案 0 :(得分: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
区分大小写。有几个关于string comparison的在线资源可以帮助您。
此外,我注意到您正在使用Worksheet_Change
并更改Sheet1
上的单元格值。我的猜测是Worksheet_Change
代表Sheet1
,是吗?如果是这种情况,那么每次修改Sheet1
时,都会再次调用该子(并且一次又一次地调用......直到它崩溃)。为防止这种情况,您需要添加
Application.EnableEvents = False
到sub的开头,然后
Application.EnableEvents = True
最后。这样,您对工作表所做的任何更改都不会触发Worksheet_Change
子。
答案 1 :(得分:0)
您可以使用EXACT(text1,text2)
功能