vba:迭代一个范围并更新另一个范围,一次一个单元格
vba: iterating through a range and updating another range one cell at a time
所有,
在Sheet 1,A列我有以下n个数字的列表
12
250
1600
100
2000
:
:
34
我查了一下table可以嵌入代码
Min Max Grade
0 100 A
100 200 B
300 500 C
:
:
1000 2000 H
2000 5000 L
5000+ M
在Sheet 2 的A 列中,根据查找table,我希望出现与sheet 1 中的数字对应的n 个等级。我只想使用 VBA 而不是 excel 公式。我该怎么做?感谢您的帮助!
你可以这样做。
Private Sub CommandButton1_Click()
Dim ws1 As Excel.Worksheet
Dim ws2 As Excel.Worksheet
Set ws1 = ActiveWorkbook.Sheets("Sheet1")
Set ws2 = ActiveWorkbook.Sheets("Sheet2")
Dim lRow As Long
Dim score As Integer
Dim strGrade As String
lRow = 1
ws1.Activate
'Loop through the rows getting the letter grade for the score.
Do While lRow <= ws1.UsedRange.Rows.count
'Get the score
If ws1.Range("A" & lRow).Value = "" Then
score = -1
Else
score = ws1.Range("A" & lRow).Value
End If
'Get the grade for the score
Select Case score
Case 0 To 100
strGrade = "A"
Case 100 To 200
strGrade = "B"
Case 300 To 500
strGrade = "C"
Case 1000 To 2000
strGrade = "H"
Case 2000 To 5000
strGrade = "L"
Case Is > 5000
strGrade = "M"
Case Else
strGrade = "?"
End Select
'Write the grade to sheet 2
ws2.Range("A" & lRow).Value = strGrade
lRow = lRow + 1
Loop
End Sub
所有,
在Sheet 1,A列我有以下n个数字的列表
12
250
1600
100
2000
:
:
34
我查了一下table可以嵌入代码
Min Max Grade
0 100 A
100 200 B
300 500 C
:
:
1000 2000 H
2000 5000 L
5000+ M
在Sheet 2 的A 列中,根据查找table,我希望出现与sheet 1 中的数字对应的n 个等级。我只想使用 VBA 而不是 excel 公式。我该怎么做?感谢您的帮助!
你可以这样做。
Private Sub CommandButton1_Click()
Dim ws1 As Excel.Worksheet
Dim ws2 As Excel.Worksheet
Set ws1 = ActiveWorkbook.Sheets("Sheet1")
Set ws2 = ActiveWorkbook.Sheets("Sheet2")
Dim lRow As Long
Dim score As Integer
Dim strGrade As String
lRow = 1
ws1.Activate
'Loop through the rows getting the letter grade for the score.
Do While lRow <= ws1.UsedRange.Rows.count
'Get the score
If ws1.Range("A" & lRow).Value = "" Then
score = -1
Else
score = ws1.Range("A" & lRow).Value
End If
'Get the grade for the score
Select Case score
Case 0 To 100
strGrade = "A"
Case 100 To 200
strGrade = "B"
Case 300 To 500
strGrade = "C"
Case 1000 To 2000
strGrade = "H"
Case 2000 To 5000
strGrade = "L"
Case Is > 5000
strGrade = "M"
Case Else
strGrade = "?"
End Select
'Write the grade to sheet 2
ws2.Range("A" & lRow).Value = strGrade
lRow = lRow + 1
Loop
End Sub