Home » excel » excel – If the first characters of a cell are GUF then Remove GUF if not leave it blank

excel – If the first characters of a cell are GUF then Remove GUF if not leave it blank

Posted by: admin May 14, 2020 Leave a comment


I am still new to coding so i apologise if i dont understand everything.

I need to check each cell of D3:D5000 if they start with GUF. Then remove the GUF from it. Else dont do anything.

This is what ive been trying to use but im getting an error Do ohne Loop:

Sub RemoveGUFfromcellsstartingwithGUF()

    Selection.End(xlDown).Offset(1, 0).Select
    ActiveCell = "end"


    Do Until ActiveCell = "end"
    If ActiveCell = "GUF*" Then
    ActiveCell.Value = Mid(Cell, 4, 999999)
    End If
    ActiveCell.Offset(1, 0).Select

End Sub

Thanks for any help/suggestions

Cells with Data

How to&Answers:

Firstly, when you are looping through cells, it’s best to use For each cell in cells, no need to change selection then.

Firstly, set a range in which you want it to run.

Sub RemoveGUFfromcellsstartingwithGUF()
    dim first_cell as Range 
    dim last_cell as Range 
    dim rng as Range
    set first_cell = ActiveSheet.Range("D1") 'first cell of your range
    set last_cell = ActiveSheet.Range("D5000") 'last cell of your range
    set rng = Range(first_cell, last_cell) 'range from first_cell to last_cell

     For Each cell in rng.cells 'looping through cells of the range
        'What you do here will be done to every cell.
        if left(cell.value, 3) = "GUF" then cell.value = Mid(cell.value,4)
     Next cell
End Sub

I hope this helps.


Is this what you are trying?

Sub Sample()
    Dim ws As Worksheet
    Dim lRow As Long, i As Long

    Set ws = Sheet1 '<~~ Change this to the relevant sheet

    With ws
        '~~> Find last row in Col D
        lRow = .Range("D" & .Rows.Count).End(xlUp).Row

        '~~> Loop through cell in Col D
        For i = 3 To lRow
            If .Range("D" & i).Value Like "GUF*" Then
                .Range("D" & i).Value = Mid(.Range("D" & i).Value, 4)
            End If
        Next i
    End With
End Sub