VBA循环从另一张表

如果我的循环没有运行在整个工作表中,我遇到了问题1.如果工作表1“testing”中的值存在工作表2“癌症”中。 然后,我想将表格2中的值“癌症”放入表格1“testing”中。 代码工作除了循环。 目前它只适用于我的第一张表中的第一条logging,然后停止。

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 

If LCase(Trim(Sheets("Cancer").Cells(y, 1).Text)) = LCase(Trim(Sheets("Tests").Cells(x, 3).Text)) and Sheets("Tests").Cells(x, 4).Value = ""如果这两个条件都不成立,那么x将永远不会循环到下一个迭代,而且您将只检查Sheet1“Tests”的相同logging,并循环遍历Sheet2“Cancer”的每个值。

你几乎可以完成所有的范围。 你错过了一个。 尝试改变行:

 Cells(x, 4) = (Trim(Sheets("Cancer").Cells(y, 3).Text)) 

 Sheets("Tests").Cells(x, 4) = (Trim(Sheets("Cancer").Cells(y, 3).Text))