我正在处理一个小脚本(下面)。该脚本遍历数据集上的行,并根据2个选择案例语句的一些意外情况在单元格中放置1或0。它工作得很完美,但我想知道是否有办法将一系列单元格组合在一起,并将其置于其中。
Sub compVal()
Dim WB As Workbook 'an object of type workbook
Dim WS1 As Worksheet ' objects of type worksheet
Set WB = ActiveWorkbook ' reference WB to the current Workbook
Set WS1 = Worksheets("Sheet1") 'Reference to Sheet 1 of the current workbook
'loop through sheet1's rows
Dim i As Integer
For i = 2 To WS1.UsedRange.Rows.Count
Select Case WS1.Cells(i, 1).Value 'first cell from row i
Case "Target"
Select Case WS1.Cells(i, 2).Value
Case 1
WS1.Cells(i, 3).Value = 1
WS1.Cells(i, 4).Value = 0
WS1.Cells(i, 5).Value = 0
WS1.Cells(i, 6).Value = 0
Case 2
WS1.Cells(i, 3).Value = 0
WS1.Cells(i, 4).Value = 0
WS1.Cells(i, 5).Value = 1
WS1.Cells(i, 6).Value = 0
End Select
Case "NonTarget"
Select Case WS1.Cells(i, 2).Value
Case 1
WS1.Cells(i, 3).Value = 0
WS1.Cells(i, 4).Value = 1
WS1.Cells(i, 5).Value = 0
WS1.Cells(i, 6).Value = 0
Case 2
WS1.Cells(i, 3).Value = 0
WS1.Cells(i, 4).Value = 0
WS1.Cells(i, 5).Value = 0
WS1.Cells(i, 6).Value = 1
End Select
End Select
Next i
End Sub
答案 0 :(得分:1)
这是代码重用的一个很好的例子:
Sub compVal()
Dim WB As Workbook 'an object of type workbook
Dim WS1 As Worksheet ' objects of type worksheet
Set WB = ActiveWorkbook ' reference WB to the current Workbook
Set WS1 = Worksheets("Sheet1") 'Reference to Sheet 1 of the current workbook
'loop through sheet1's rows
Dim i As Long ' USE LONG FOR CELL REFERENCES, THERE ARE A LOT OF ROWS POSSIBLE : )
For i = 2 To WS1.UsedRange.Rows.Count
Select Case WS1.Cells(i, 1).Value 'first cell from row i
Case "Target"
Select Case WS1.Cells(i, 2).Value
Case 1
AddColumns WS1, i, 1, 0, 0, 0
Case 2
AddColumns WS1, i, 0, 0, 1, 0
End Select
Case "NonTarget"
Select Case WS1.Cells(i, 2).Value
Case 1
AddColumns WS1, i, 0, 1, 0, 0
Case 2
AddColumns WS1, i, 0, 0, 0, 1
End Select
End Select
Next i
End Sub
Sub AddColumns(WS As Worksheet, i As Long, c As Variant, d As Variant, e As Variant, f As Variant)
WS.Cells(i, 3).Resize(1, 4).Value = Array(c, d, e, f)
End Sub
还可以引入其他效率,例如用一个整数替换四个参数c,d,e和f,其中
0 = 0,0,0,0
1 = 1,0,0,0
2 = 0,1,0,0
...
15 = 1,1,1,1