来自另一张纸的 VBA 循环

标签 vba excel loops

我的循环无法在整个工作表 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/

相关文章:

excel - 将用户窗体文本框值中的更改保存为新的默认值

sql - Excel VBA 使用 InstantClient 连接到远程 Oracle 数据库

VBA Excel 中的多线程

c# - 如何将基于字符串的时间转换为 hh :mm format in excel using EPPlus?

excel - Visual Basic Excel 函数 - 范围偏移错误

javascript - Angular JS 将对象复制到另一个对象到 for 循环中

vba - 将 Excel 工作表(部分)的范围导出到 CSV

javascript - Javascript 中对象的特定属性

c# - 有什么方法可以使用循环重复此过程两次?

excel - 数据透视表返回范围内的第一个值