我的循环无法在整个工作表 1 中运行,因此遇到问题。如果工作表 1“测试”中的值存在于工作表 2“癌症”中。然后我希望将第 2 张“癌症”中的值放入第 1 张“测试”中。除了循环之外,该代码可以工作。目前,它仅适用于我的第一张表中的第一条记录,然后停止。
Sub Testing()
Dim x As Long
Dim y As Long
x = 2
y = 2
Do While Sheets("Cancer").Cells(y, 1).Value <> ""
If LCase(Trim(Sheets("Cancer").Cells(y, 1).Text)) = LCase(Trim(Sheets("Tests").Cells(x, 3).Text)) Then
If Sheets("Tests").Cells(x, 4).Value = "" Then
Cells(x, 4) = (Trim(Sheets("Cancer").Cells(y, 3).Text))
x = x + 1
End If
End If
y = y + 1
Loop
End Sub
最佳答案
我会使用两个 for 循环
for y = 2 to 10000 'the range your values are found
if Sheets("Cancer").Cells(y, 1).Value <> "" then
for x = 2 to 10000 'the range your values are in
If LCase(Trim(Sheets("Cancer").Cells(y, 1).Text)) = LCase(Trim(Sheets("Tests").Cells(x, 3).Text)) and Sheets("Tests").Cells(x, 4).Value = "" Then
Cells(x, 4) = (Trim(Sheets("Cancer").Cells(y, 3).Text))
End If
next
end if
next
循环没有贯穿整个工作表 1 的原因是以下两行:
如果 LCase(Trim(Sheets("癌症").Cells(y, 1).Text)) = LCase(Trim(Sheets("Tests").Cells(x, 3).Text)) 和 Sheets( "测试").Cells(x, 4).Value = ""
如果这些条件不是都为真,则 x 将永远不会循环到下一次迭代,并且您将循环遍历 Sheet2“Cancer”的每个值,同时仅检查 Sheet1“Tests”的相同记录。
关于来自另一张纸的 VBA 循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43121489/