![](/img/trans.png)
[英]How to populate or update column value in an excel sheet based on data values in another reference column
[英]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工作表 。
通常在此工作表中約有5000行
和
帶列的搜索詞工作表.....
通常在此表中約1-20行
您可以嘗試以下方法。 我們在這里有2個主要工作。
找到匹配項。 當然,您可以嘗試使用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
更新記錄。 由於我們已經找到了包含學生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.