繁体   English   中英

如何使用 VBA 更新循环内的范围

[英]How to Update Range within a Loop using VBA

我有三列:名称、接受/同义词、接受名称的同义词。 该脚本旨在循环通过“接受/同义词”列,当值等于“接受”时,需要将范围 object 设置为 Cells(x, 9),直到达到另一个“接受”值。 如果以下值是“同义词”,则 Cells(x,4) 的值应连接到最近的范围 Cells(x,9) unitl 达到“可接受的”值。 我正在尝试更新范围的值,该范围应包括最近“已接受”单元格之前的所有同义词的名称。 我的脚本不会在每次迭代时更新范围,因为有一个新的“已接受”行,而是一遍又一遍地替换相同的范围值。 我已尽我所能对此进行解释,但如有任何帮助,我将不胜感激,我准备澄清任何细节。 提前致谢。

Private Sub CommandButton2_Click()
 
    Dim x As Long
    Dim rng As Range
    Dim acc As String
    Dim syn As String
    Dim updRng As Range
    
    x = 157
    

    Set rng = Cells(157, 9)
    
    
    Do While x < 5000
        If Cells(x, 5).Value = "synonym" Then
            syn = Cells(x, 4).Value
            acc = acc & "; " & syn
            acc = Right(acc, Len(acc) - 2) ' "-2" the length of "; "
            rng.Value = acc '<---This is the problematic line
        Else
            Set updRng = Cells(x, 9)
            acc = ""
            If Cells(x + 1, 5).Value = "synonym" Then 'if the cell below is synonym
                updRng.Value = acc
            End If
        
        End If
        
        x = x + 1
    Loop
End Sub

我相信我只是自己解决了它......这是现在主要工作的代码。 看来我需要另一个条件,那就是“ElseIf”

Private Sub CommandButton2_Click()

     
    Dim x As Long
    Dim rng As Range
    Dim acc As String
    Dim syn As String
    Dim updRng As Range
    
    x = 157
    'y = 9

    Set rng = Cells(157, 9)
    
    
    Do While x < 5000
        If Cells(x, 5).Value = "synonym" Then
            syn = Cells(x, 4).Value
            acc = acc & "; " & syn
            acc = Right(acc, Len(acc) - 2) ' "-2" the length of "; "
        ElseIf Cells(x + 1, 5).Value = "accepted" Then
            updRng.Value = acc
        Else
            Set updRng = Cells(x, 9)
            acc = ""
            If Cells(x + 1, 5).Value = "synonym" Then 'if the cell below is synonym
                updRng.Value = acc
            End If
        
        End If
        
        x = x + 1
    Loop
End Sub

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM