【发布时间】:2012-05-30 13:57:43
【问题描述】:
我正在尝试比较来自不同工作表的两个文本单元格(如 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 都不管用。
【问题讨论】:
-
这在 VBA 项目结构中保存在哪里?它应该保存在您要处理更改事件的每个工作表中。另外,你不需要循环,If 语句条件应该是
Range("A2").Text = Sheets(1).Range("A2").Text -
所以代码会抛出一个错误(哪个和在哪里?)或者条件永远不会评估为 True?
-
@MarkM 我只有在 Sheet1 中有这个。你说的我试过了,还是不行。
-
@PaulB。我可以完美地编译代码。问题是你所说的条件。
-
尝试切换
EnableEvents,正如我在回答中提到的那样,看看是否有效。