Goal: Load a selection of one or multiple cells in a column and then split the data by "_". Use the string and count the number of each letter at each position.
I am trying to calculate the frequency of each letter A, B, C and D at every position of all the selected range of strings and print them to the next available column.
Option Explicit
Sub Count_ABCD()
Dim cell As Range
'Next task is to select a range of sequences and do the following
'Trying to use the selection and accesing one cell at a time.
For Each cell In Cells(ActiveCell.Column, "A")
Dim Yourseq As String
Dim arr() As String
Dim StoreA() As Variant
Dim StoreB() As Variant
Dim StoreC() As Variant
Dim StoreD() As Variant
Dim i As Long
Dim Destination As Range
Yourseq = cell.Value 'take a sequence and store it in a variable
Range("G2").Value = Len(Yourseq) 'show the length of the sequence in the next cell
arr = Split(Yourseq, "_")
'Apparently for performance purposes we need to resize our dynamic array in VBA
ReDim StoreA(1 To Len(arr(1)))
ReDim StoreB(1 To Len(arr(1)))
ReDim StoreC(1 To Len(arr(1)))
ReDim StoreD(1 To Len(arr(1)))
Set Destination = Range("J2:K25") 'Start printing here
'First take one sequence length and create 4 arrays (for each letter)
' and fill them with 0s
For i = 1 To Len(arr(1))
StoreA(i) = 0
StoreB(i) = 0
StoreC(i) = 0
StoreD(i) = 0
Next
For i = 1 To Len(arr(1))
'Check whether the string is A/B/C/D then add plus one to each array index
If UCase(Mid(arr(1), i, 1)) = "A" Then
StoreA(i) = StoreA(i) + 1
ElseIf UCase(Mid(arr(1), i, 1)) = "B" Then
StoreB(i) = StoreB(i) + 1
ElseIf UCase(Mid(arr(1), i, 1)) = "C" Then
StoreC(i) = StoreC(i) + 1
ElseIf UCase(Mid(arr(1), i, 1)) = "D" Then
StoreD(i) = StoreD(i) + 1
End If
Next
'Range("I2").Value = (UBound(StoreA) - LBound(StoreA) + 1)
Range("I2").Value = arr(1)
'Resize an array to the preferred range of values
Set Destination = Destination.Resize(1, UBound(StoreA))
Destination.Value = StoreB 'Print an array to the preferred range of values
Next cell
End Sub
The output should be printed to the next available column. I wrote Destination = Range ("J2:K25") cause I didn't know a better way.



