如果数据存在于列中,则更新单元格

假设有两个工作表:工作表1,工作表2

工作表1有一个名为'Number'的列

工作表2也是一个名为'Number'的列

现在我在工作表2的“数字”列中input一个数字。

我现在需要将我在工作表1的“数字”中input的数字与工作表1的“数字”列进行匹配。

如果匹配,则允许在工作表2上input,否则抛出错误'Invalid Data'

  • 工作表2的“数字”列不应该允许重复。

你们能为我解决同样的问题:)

没有必要使用VBA。 你可以使用数据validation:

工作表Sheet1:

在这里输入图像说明

Sheet2中:

在表2中select整个列“数字” 。 进入数据 – >数据validation 。 select自定义并input公式:

 =AND(ISNUMBER(MATCH($A1,Sheet1!$A:$A,0)),COUNTIF($A:$A,$A1)<2) 

其中Sheet1!$A:$A sheet1中 “Numbers”列Sheet1!$A:$A地址。 $A:$A表单2中 “数字”列的地址。

  • 部分ISNUMBER(MATCH($A1,Sheet1!$A:$A,0))只允许从sheet1input值。
  • 部分COUNTIF($A:$A,$A1)<2不允许重复

在这里输入图像说明

select“错误警报”选项卡并input错误消息。

在这里输入图像说明

完成!

应该沿着这些线路工作:

 Private Sub Worksheet_Change(ByVal Target As Range) Dim TarColumn as Integer 'stores the column number of the modified cell TarColumn = Target.Column 'sets the column number If TarColumn = 1 Then 'replace 1 with the column number of your Number Column Dim RowCountA as Long 'stores the amount of rows in your worksheets Dim RowCountB as Long Dim a, b 'will store the numbers from the number columns RowCountA = Worksheets("Sheet1").Cells(Rows.Count,1).End(xlUp).Row 'find the last row of data RowCountB = Worksheets("Sheet2").Cells(Rows.Count,1).End(xlUp).Row a = Worksheets("Sheet1").Cells(1,1).Resize(RowCountA,1) 'copys the numbers into the arrays b = Worksheets("Sheet2").Cells(1,1).Resize(RowCountB,1) For i = 0 To RowCountA - 1 'checks to see if it is in the first sheet If Target.Value = a(i,1) then MsgBox("Invalid Data") Target.Value = "" Exit Sub End If Next For i = 0 to RowCountB - 2 'ensures no duplication in the second sheet If Target.Value = b(i,1) then MsgBox("Invalid Data") Target.Value = "" Exit Sub End If Next End If End Sub 

您可能需要修改.cells(1,1)以适应代码,具体取决于工作表中的标题和位置。