查找列中是否已存在值

时间:2018-03-25 08:40:34

标签: excel-vba vba excel

我添加了一个包含新成员详细信息的行。以下代码可以使用

With Worksheets("Enroll Course")
 'insert blank row 8 in Course sheet and copy details to it
      Worksheets(.Range("C6").Value).Rows(8).Insert Shift:=xlShiftDown
     .Range("C5").Copy Worksheets(.Range("C6").Value).Range("A8") 'member name
End With

会员名称在这里.Range(" C5")。

工作表在这里是工作表(.Range(" C6")。值)

如果该成员已经存在于工作表中,那么我想找到它们所在的行并将详细信息粘贴到B列中的该行而不是第8行,而不是插入并粘贴到A8。 如何查找成员是否已在工作表中?

1 个答案:

答案 0 :(得分:0)

I tried this with the code below, but there may be simpler ways.

If I understand the question correctly, when the member name already exists you want to post data to column B of the row with the member name.

Dim AnsRng As Range
Dim Sheet As Worksheet
Dim LastRow As Long

Set Sheet = Worksheets("Enroll Course")

'Use autofilter to check if the member name is already in target worksheet
Worksheets(Sheet.Range("C6").Value).AutoFilterMode = False
'A2:B8 here is an example range that you want to search. 
'Assumes column to be searched for existing member name is column A.
Worksheets(Sheet.Range("C6").Value).Range("A2:B8").AutoFilter Field:=1, _
Criteria1:=Worksheets("Enroll").Range("C4").Value
Set AnsRng = Worksheets(Sheet.Range("C6").Value). _
UsedRange.SpecialCells(xlCellTypeVisible)

'If name already exists, add content to column B
If AnsRng.Rows.Count > 1 Then
    'Find the row where the member name exists
    LastRow = Worksheets(Sheet.Range("C6").Value).Cells. _
    SpecialCells(xlCellTypeLastCell).Row
    'Paste data "Enroll Course" C6 into column B of selected row
    Sheet.Range("C6").Copy Worksheets(Sheet.Range("C6").Value). _
    Range("B" & (LastRow))
    Worksheets(Sheet.Range("C6").Value).AutoFilterMode = False
Else
'If name does not exist
    With Worksheets("Enroll")
   'insert blank row 8 in Course sheet and copy details to it
        Worksheets(.Range("C6").Value).Rows(8).Insert Shift:=xlShiftDown
        'Insert member name
        .Range("C5").Copy Worksheets(.Range("C6").Value).Range("A3")
        Worksheets(Sheet.Range("C6").Value).AutoFilterMode = False
    End With
End If