HiveBrain v1.2.0
Get Started
← Back to all entries
patternModerate

Assigning value to cells with Excel VBA

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
excelwithvaluecellsvbaassigning

Problem

I have an Excel Worksheet consisting of two columns, one of which is filled with strings and the other of which is empty. I would like to use VBA to assign the value of the cells in the empty column based on the value of the adjacent string in the other column.

Dim regexAdmin As Object 
Set regexAdmin = CreateObject("VBScript.RegExp") 
regexAdmin.IgnoreCase = True
regexAdmin.Pattern = "Admin" 

Dim i As Integer
For i = 1 To 10 'let's say there is 10 rows
    Dim j As Integer
    For j = 1 To 2
        If regexAdmin.test(Cells(i, j).Value) Then
            Cells(i, j + 1).Value = "Exploitation"
        End If
    Next j
Next i


The problem is that when using this loop for a big amount of data, it takes way too long to work and, most of the time, it simply crashes Excel.

Does anyone know a better way of doing this?

Solution

The short answer is:

Don't use vba, use a formula. In particular, a combination of IF and SEARCH.

=IF(SEARCH($A1,"Admin")>0,"Exploitation","")


But this is code review, so let's do that anyway.

-
Regex is slow. It seems that you're only using it for it's case insensitivity. Given that, you can directly compare cell values by using StrComp with the vbTextCompare option. (useful article on StrComp)

-
i and j are typically used for loop counters, but row and col make more sense in this case.

Here is what this could could look like:

Dim row As Integer
For row = 1 To 10 'let's say there is 10 rows
    Dim col As Integer
    For col = 1 To 2
        If StrComp("Admin",Cells(row, col).Value,vbTextCompare) Then
            Cells(row, col + 1).Value = "Exploitation"
        End If
    Next col
Next row

Code Snippets

=IF(SEARCH($A1,"Admin")>0,"Exploitation","")
Dim row As Integer
For row = 1 To 10 'let's say there is 10 rows
    Dim col As Integer
    For col = 1 To 2
        If StrComp("Admin",Cells(row, col).Value,vbTextCompare) Then
            Cells(row, col + 1).Value = "Exploitation"
        End If
    Next col
Next row

Context

StackExchange Code Review Q#59382, answer score: 13

Revisions (0)

No revisions yet.