使用循环将 1 个工作表中的值替换为另一个工作表

Replace value from 1 worksheet to another using a loop

我需要一种方法来将我的主要工作sheet(主要)中的值替换为我的次要工作sheet(更新)中的值。

我的主要工作sheet 有这些列名称:EmpName、EmpID、EmpSupervisor、Emp Director。

和我的副业sheet:EmpName、EmpID、New Sup、NewDir、Status。

如果第 2 部作品sheet 中的条目状态列为 "mismatch",它将自动传递 "new sup" and/or "new dir" 数据相应的EmpID并在主sheet.

中覆盖"empsupervisor"and/or"empdirector"

像这样的东西,我只是不能把它放在 vba 可以理解的正确语法中。

 for each STATUS = Mismatch in worksheet2

 update worksheet1.column("Empsupervisor") with worksheet2.column("New Sup").value

 where worksheet1.column("EmpID") = worksheet2.column("EmpID")

 next

此方法遍历所有行,检查不匹配,找到员工 ID 行,然后将新主管和新主管移动到第一个 sheet:

Sub TestIt()

Dim LastRow As Long, CurRow As Long, DestRow As Long, DestLast As Long
Dim ws1 As Worksheet, ws2 As Worksheet

Set ws1 = Sheets("Name of main worksheet")
Set ws2 = Sheets("Name of secondary worksheet")

LastRow = ws2.Range("B" & Rows.Count).End(xlUp).Row
DestLast = ws1.Range("B" & Rows.Count).End(xlUp).Row

For CurRow = 2 To LastRow 'Assumes first row has headers
    If ws2.Range("E" & CurRow) = "mismatch" Then 'Assumes mismatch is in column E
        If Not ws1.Range("B2:B" & DestLast).Find(ws2.Range("B" & CurRow).Value, LookIn:=xlValues, LookAt:=xlWhole) Is Nothing Then
            DestRow = ws1.Range("B2:B" & DestLast).Find(ws2.Range("B" & CurRow).Value, LookIn:=xlValues, LookAt:=xlWhole).Row
        End If
        ws1.Range("C" & DestRow).Value = ws2.Range("C" & CurRow).Value 'assumes supervisor is in column C in both sheets
        ws1.Range("D" & DestRow).Value = ws2.Range("D" & CurRow).Value 'assumes director is in column D in both sheets
    End If
Next CurRow

End Sub

LastRow的解释:

Range("B" & Rows.Count) goes to the last row on the sheet which is Row 1,048,576 in Excel '07, '10, and '13. So imagine Range("B1048576"). Then it performs End(xlUp) which is "Equivalent to pressing END+UP ARROW" according to MSDN. This will go to the first cell in column B that is non-blank above B1048576. The last command .Row returns that row number of the cell.

DestRow的解释:

We are using a Range.Find() method to identify if the employeeID exists in the first worksheet and on what row it exists. Range.Find() returns a range which is why I use Range.Find().Row because when found, we want to know the row we are going to. However, if Find() doesn't find anything, it returns Nothing and Nothing.Row would error. Therefore I do a quick If Not Find() Nothing to make sure the value is found.