在VBA中使用数组来应用密钥来重新编码项目响应

时间:2017-01-23 23:56:00

标签: arrays vba excel-vba excel

我有一个数据集,其中包含对多个测试的项目响应。我想基于正确的响应重新编码响应,可以从文件中读取。测试具有不同的长度,记录的数量可以根据测试和应用的数据集而变化。例如,数据集可具有400条记录,其具有对50个阅读项目的响应,40个数学项目30个拼写项目等。 目前我正在重新编码每个项目的响应,如下面的代码所示。我想阅读我的50个正确答案并将其应用于相应的50列(CV:ES)中的响应,然后使用相同/相似的代码结构应用于其他列中的其他测试响应。

Sub readscore27()
Dim readkey(1) As String
readkey(1) = "A"

Dim MyRange As Range
Dim MyCell As Range
Sheets("output2").Select
'Step 2:  Define the target Range.
Set MyRange = Range("dv2", Range("dv" & Rows.Count).End(xlUp))
'Step 3:  Start looping through the range.
For Each MyCell In MyRange
'Step 4:  Do something with each cell.
  If MyCell.Value = "^" Then
  MyCell.Value =readkey(1)
 ElseIf MyCell.Value = "--" Then
  MyCell.Value = "-"
 ElseIf IsEmpty(MyCell) Then
  MyCell.Value = ""
 End If
'Step 5: Get the next cell in the range
Next MyCell
End Sub

1 个答案:

答案 0 :(得分:0)

您可以通过向readscore添加一些参数来使代码更通用。

以下示例。

Sub Tester()

    readscore "DV", "A"
    readscore "DW", "B"
    readscore "DX", "C"

End Sub



Sub readscore(colLetter, readkey)
    Dim c As Range, myRange As Range, v

    With Sheets("output2")
        Set myRange = .Range(.Cells(2, colLetter), _
                      .Cells(.Rows.Count, colLetter).End(xlUp))
    End With

    For Each c In myRange
        v = c.Value
        If v = "^" Then
            c.Value = readkey
        ElseIf v = "--" Then
            c.Value = "-"
        ElseIf Len(v) = 0 Then
            c.Value = ""
        End If
    Next c
End Sub