我是VBA的新手,我正在使用的一个例子(下图),正在使用If函数;在这种情况下,根据A1中的“得分”,一些文本将显示在B1中。
我明白这很好,但我想知道你将如何将它应用于一系列细胞。从A1到A10说,根据分数,文本显示在B1到B10中。
我尝试过搜索,但我尝试过使用FOR循环,但它只显示A列中最后一个条目的文本。
有人可以帮助解释将这类物品应用于一系列细胞的“标准”方式吗?
由于
Dim note As Integer, score_comment As String
note = Range("A1")
'Comments based on the score
If note = 6 Then
score_comment = "Excellent score !"
ElseIf note = 5 Then
score_comment = "Good score"
ElseIf note = 4 Then
score_comment = "Satisfactory score"
ElseIf note = 3 Then
score_comment = "Unsatisfactory score"
ElseIf note = 2 Then
score_comment = "Bad score"
ElseIf note = 1 Then
score_comment = "Terrible score"
Else
score_comment = "Zero score"
End If
'Comments in B1
Range("B1") = score_comment
答案 0 :(得分:0)
以下是一个例子:
Sub LoopExample()
Dim rng As Range, cl As Range, note as integer
Set rng = Range("A1:A10")
For Each cl In rng
note = cl.value
If note = 6 Then
cl.Offset(0, 1) = "Excellent score !"
ElseIf note = 5 Then
cl.Offset(0, 1) = "Good score"
ElseIf note = 4 Then
cl.Offset(0, 1) = "Satisfactory score"
ElseIf note = 3 Then
cl.Offset(0, 1) = "Unsatisfactory score"
ElseIf note = 2 Then
cl.Offset(0, 1) = "Bad score"
ElseIf note = 1 Then
cl.Offset(0, 1) = "Terrible score"
Else
cl.Offset(0, 1) = "Zero score"
End If
Next cl
End Sub
注意:
note
在循环中定义offset(0,1)
获取B列中的附属单元格。现在不需要score_comment
答案 1 :(得分:0)
Dim lastRow As Integer
Dim i As Integer
'lastRow is the amount of rows in columns 1 (dynamic)
lastRow = Cells(Rows.Count, 1).End(xlUp).Row
For i = 1 To lastRow
If Cells(i, 1).Value = 1 Then
Cells(i, 1).Offset(0, 1).Value = "Comment ONE"
ElseIf Cells(i, 1).Value = 2 Then
Cells(i, 1).Offset(0, 1).Value = "Comment TWO"
ElseIf Cells(i, 1).Value = 3 Then
Cells(i, 1).Offset(0, 1).Value = "Comment THREE"
ElseIf Cells(i, 1).Value = 4 Then
Cells(i, 1).Offset(0, 1).Value = "Comment FOUR"
ElseIf Cells(i, 1).Value = 5 Then
Cells(i, 1).Offset(0, 1).Value = "Comment FIVE"
ElseIf Cells(i, 1).Value = 6 Then
Cells(i, 1).Offset(0, 1).Value = "Comment SIX"
End If
Next i