'VBA Loop an array and reset
I want to check if my data is within an array and if so it should write it in a new cell.
My problem:
If two entries are the same and follow each other my if statement wont find it in the for loop because my loop doesn't reset.
How can I fix this?
Sub Tester()
Dim ArtikelZgm As Variant
ArtikelZgm = Worksheets("Artikel").Range("A1").CurrentRegion
Dim a As Long
For a = LBound(ArtikelZgm, 1) To UBound(ArtikelZgm, 1)
For b = 2 To 100
If ArtikelZgm(a, 3) = Worksheets("Bestellung Lidl").Cells(b, "F").Value Then
Worksheets("Bestellung Lidl").Cells(b, "H").Value = ArtikelZgm(a, 1)
Worksheets("Bestellung Lidl").Cells(b, "I").Value = ArtikelZgm(a, 5)
b = b + 1
End If
Next b
Next a
End Sub
Solution 1:[1]
I would use Match instead of the nested loop:
Sub Tester()
Dim ArtikelZgm As Variant, m
Dim b As Long, wsBL As Worksheet, wsA As Worksheet
Set wsA = Worksheets("Artikel")
Set wsBL = Worksheets("Bestellung Lidl")
ArtikelZgm = wsA.Range("A1").CurrentRegion.Value
For b = 2 To 100
'using Match is faster than a nested loop
m = Application.Match(wsBL.Cells(b, "F").Value, wsA.Columns("C"), 0)
If Not IsError(m) Then 'got a match if `m` is not an error value
wsBL.Cells(b, "H").Value = ArtikelZgm(m, 1)
wsBL.Cells(b, "I").Value = ArtikelZgm(m, 5)
End If
Next b
End Sub
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Tim Williams |
