【问题标题】:VBA Loop from another sheet从另一张表中循环 VBA
【发布时间】:2017-03-30 14:58:45
【问题描述】:

我的循环没有在整个工作表 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

【问题讨论】:

  • 你有没有通过代码来检查发生了什么?

标签: vba excel loops


【解决方案1】:

我会使用两个 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 中运行的原因是因为这两行: 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 将永远不会循环到下一次迭代,并且您将遍历 Sheet2“Cancer”的每个值,同时只检查 Sheet1“Tests”的相同记录。

【讨论】:

    【解决方案2】:

    您几乎已经达到了所有范围的资格。你错过了一个。换行试试:

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

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

    【讨论】:

    • 好地方,但不确定如果代码第一次工作,这可能是原始问题。
    • 你说得对,我以为它在某处更改了活动表,但事实并非如此。是我,还是这只是一个查找的 vba 模拟?
    • 不确定!类似的东西。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-06-12
    • 2019-04-21
    • 1970-01-01
    • 1970-01-01
    • 2017-12-17
    相关资源
    最近更新 更多