繁体   English   中英

如何基于另一个工作表中的列中的值查找和更新Excel工作表中的行?

[英]How to find and update a row in an Excel sheet based on a value in a column in another sheet?

寻找一些指导。 我有两个Excel工作表(1)masterdata(2)Searchterms。

搜索字词包含带有学生ID的单个列A。
Masterdata包含与学生有关的所有数据。

我以前从未在Excel中使用过VBA,因此请寻找一些指导

我需要做的是从StudentIDs表(A1)中获取第一个StudentID,然后在Masterdata表中搜索它。 如果找到,则使用几条信息更新该工作表(主数据)中的列...如果找不到,则移至StudentIds工作表中col A2等中的下一个StudentID。

Sub FindMatchingValue() 
Dim i As Integer
  Dim strValueToFind As String

    strValueToFind = Worksheets("StudentID").Range("A1").Value
    For i = 1 To 500
        If Cells(i, 1).Value = strValueToFind Then
            MsgBox ("Found value on row " & i)
            'update row i col B  = 'new name' - found in StudentID sheet col B
            'update row i col C  = 'new class number '- found in StudentID sheet col C
            Exit Sub
        End If
    Next i

    MsgBox ("Value not found in the range!")
End Sub

工作簿包含两个工作表,即具有列的masterdata工作表

  • 上校学生证
  • B列名称
  • C类课程编号
  • 上校D注册日期
  • Col E开始日期
  • 上校学生贷款
  • 上校G评论
  • COL H最后编辑

    通常在此工作表中约有5000行

带列的搜索词工作表.....

  • 上校学生证
  • B列名称
  • C类课程编号
  • 上校D评论

    通常在此表中约1-20行

您可以尝试以下方法。 我们在这里有2个主要工作。

  1. 找到匹配项。 当然,您可以尝试使用For Loop ,但是,让我们利用Excel的内置方法Find Find方法返回一个Range对象,这意味着它将在masterdata表中返回包含学生ID的范围

     Dim sID As Range, whattofind As Range Dim mSh As Worksheet, sSh As Worksheet Set mSh = Worksheets("masterdata") '// you can adjust to suit // Set sSh = Worksheets("searchitems") Set whattofind = sSh.Range("A1") With mSh '// here you use the Find Method of the Range Object // Set sID = .Range("A:A").Find(What:=whattofind.Value2, _ After:=.Range("A" & .Rows.Count)) '// take note that we supplied the After argument // '// that is to cover the entire range from top to bottom // End With 
  2. 更新记录。 由于我们已经找到了包含学生ID的 Range,因此我们只需要更新一些列即可。 为此,我们将使用Excel的内置方法Offset 请注意,由于我们在searchitems工作表中有多个条目,因此我们需要执行多次。 因此,我们也将使用For Loop

     Dim sID As Range, whattofind As Range, i As Long Dim mSh As Worksheet, sSh As Worksheet Set mSh = Worksheets("masterdata") '// you can adjust to suit // Set sSh = Worksheets("searchitems") For i = 1 To 500 '// depends on your list // Set whattofind = sSh.Range("A" & i) With mSh Set sID = .Range("A:A").Find(What:=whattofind.Value2, _ After:=.Range("A" & .Rows.Count)) If Not sID Is Nothing Then '// check if a match is found // '// just play around and adjust on how many columns you need updated // sID.Offset(, 2) = whattofind.Offset(, 2) '// here we update Class number // sID.Offset(, 6) = whattofind.Offset(, 3) '// here we update Comments // End If End With '// reset your ranges // Set sID = Nothing Set whattofind = Nothing Next 

我希望这有助于您入门。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM