The original code has some problems, I’ll rephrase and explain some points.
Example 01 - Following the original logic of a For
for each test phrase:
Sub testeFraseExemplo1()
Dim linha As Integer 'declara a linha como inteiro
For linha = 1 To 30 'verificará da linha 1 até a 30
If Cells(linha, 2) = "01 dormitório" Then 'verifica se é o texto esperado
Cells(linha, 2).Copy Cells(linha, 1) 'copia a célula da linha do for coluna B, para a célula mesma linha coluna A
Exit For 'encerra o for, pois já encontrou
End If 'fecha if
Next linha 'próxima linha, se não foi encerrado no if verdadeiro
For linha = 1 To 30
If Cells(linha, 2) = "02 Dormitórios" Then
Cells(linha, 2).Copy Cells(linha, 1)
Exit For
End If
Next linha
End Sub
Note that you do not need to use another line name (as you did with i and j). You can reuse it, the For
redefine to 1 To 30
(or another range you set when declaring it). The rest of the code is identical to the top block, changing the phrase only.
Example 02 - It is possible to use the same For
, with more than one If
. It is also possible to use the same If
with more than one condition (test phrase).
Sub testeFraseTipoExemplo2()
Dim linha As Integer
For linha = 1 To 30
If Cells(linha, 2) = "01 dormitório" Or _
Cells(linha, 2) = "02 Dormitórios" Then 'pode ir acrescentando outros Or ou And
Cells(linha, 2).Copy Cells(linha, 1)
End If
Next linha
End Sub
Choosing one or the other depends on the final design, is related to maintenance, performance of having multiple For analyzing the same lines and etc. Having to indicate the second option, but everything depends.
In the description is "and glue in the cell before it" (previous is the immediately above?), but in the example screen, is fixed in the "A1" (GLUE HERE THE SENTENCE...). What is expected? If it is in the "A1", the "01 dormitory" will be superimposed by the "02 Dormitory", for example.
– Jean Barbosa
Wrong description. It’s "glue on the left cell"
– Matheus Smark