【问题标题】:How to Update Range within a Loop using VBA如何使用 VBA 更新循环内的范围
【发布时间】:2023-03-04 19:50:01
【问题描述】:

我有三列:名称、接受/同义词、接受名称的同义词。该脚本旨在循环通过“接受/同义词”列,当值等于“接受”时,需要将范围对象设置为 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

【问题讨论】:

    标签: excel vba loops object range


    【解决方案1】:

    我相信我自己刚刚解决了它......这是现在大部分工作的代码。看来我需要另一个条件,那就是“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
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-08-03
      • 2019-11-14
      • 1970-01-01
      相关资源
      最近更新 更多