Reputation: 75
Im working on a little script (below). The script iterates through rows on a data set and places either a 1 or 0 in a cell based on some contingencies of 2 select case statements. It works perfect, but I want to know if there's a way to group the range of cells together that are getting a 0 placed within them.
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
Upvotes: 0
Views: 1717
Reputation: 2693
This is a great example of code re-use:
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
There are other efficiencies that could be introduced, such as replacing the four arguments c,d,e and f with a single integer where
0 = 0,0,0,0
1 = 1,0,0,0
2 = 0,1,0,0
...
15 = 1,1,1,1
Upvotes: 1