[英]How to update the value in a range of cells using a Loop in Excel 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.