Sub TestResult()
Dim Score As Integer, Result As String
Score = Range("A1:A5").Value
If Score >= 60 Then
Result = "pass"
Else
Result = "fail"
End If
Range("B1:B5").Value = Result
End Sub
Score = Range("A1:A5").Value
这是问题所在。我应该如何更改它才能工作?
答案 0 :(得分:1)
With ActiveSheet.Range("A1:A5")
.Offset(0, 1).Value = .Parent.Evaluate("=IF(" & .Address() & ">60,""Pass"",""Fail"")")
End With
答案 1 :(得分:0)
对于此答案,我使用Sheet1。如果我理解正确,那么您想在每个结果通过或失败时放在旁边吗?
尝试:
Option Explicit
Sub TestResult()
Dim ScoreList As Range, Score As Range, Result As String
With ThisWorkbook.Worksheets("Sheet1")
Set ScoreList = .Range("A1:A5")
For Each Score In ScoreList
If Score.Value >= 60 Then
Score.Offset(0, 1).Value = "Pass"
Else
Score.Offset(0, 1).Value = "Fail"
End If
Next
End With
End Sub
答案 2 :(得分:0)
首先,您可以使用B1:B5范围内的公式进行此操作
=IF(A:A>=60,"pass","fail")
或者您可以使用VBA编写该公式
Range("B1:B5").Formula = "=IF(A:A>=60,""pass"",""fail"")"
forumlas的优势在于,每当分数变化时,它们都会自动更新。如果您使用VBA(不使用公式)进行操作,结果将不自动更新。
如果您仍然想使用VBA进行操作,则需要遍历数据并测试每个分数。使用阵列执行此操作可能是使用VBA最快的方法。
Option Explicit
Public Sub TestResult()
Dim ScoresArr As Variant 'read values into an array
ScoresArr = Worksheets("Sheet1").Range("A1:A5").Value
Dim ResultArr As Variant 'create result array with same size
ReDim ResultArr(1 To UBound(ScoresArr, 1), 1 To UBound(ScoresArr, 2))
Dim iRow As Long
For iRow = 1 To UBound(ScoresArr, 1) 'loop through array
If ScoresArr(iRow, 1) >= 60 Then 'test each score
ResultArr(iRow, 1) = "pass"
Else
ResultArr(iRow, 1) = "fail"
End If
Next iRow
Worksheets("Sheet1").Range("B1:B5").Value = ResultArr 'write results array back to cells
End Sub
如果要让用户选择分数范围,请使用Application.InputBox和Type:=8
,如下所示:
Option Explicit
Public Sub TestResult()
Dim ScoresRange As Variant
On Error GoTo CANCEL_TEST 'the next line will throw an error if cancel is pressed
Set ScoresRange = Application.InputBox(Prompt:="Select the scores", Title:="Test Result", Type:=8)
On Error GoTo 0 'always re-activate error reporting!!!
If ScoresRange.Columns.Count <> 1 Then 'test if only one column was selected
MsgBox "Only selection of one column is allowed."
Exit Sub
End If
Dim ScoresArr As Variant 'read values into an array
ScoresArr = ScoresRange.Value
Dim ResultArr As Variant 'create result array with same size
ReDim ResultArr(1 To UBound(ScoresArr, 1), 1 To UBound(ScoresArr, 2))
Dim iRow As Long
For iRow = 1 To UBound(ScoresArr, 1) 'loop through array
If ScoresArr(iRow, 1) >= 60 Then 'test each score
ResultArr(iRow, 1) = "pass"
Else
ResultArr(iRow, 1) = "fail"
End If
Next iRow
ScoresRange.Offset(ColumnOffset:=1).Value = ResultArr 'write results array back to cells
CANCEL_TEST:
End Sub