Skip to content

Instantly share code, notes, and snippets.

@rossant
Last active December 2, 2016 20:26
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rossant/3af66b1e06410b2344578ca6d458fa9b to your computer and use it in GitHub Desktop.
Save rossant/3af66b1e06410b2344578ca6d458fa9b to your computer and use it in GitHub Desktop.
VBA code to find French cities associated to a given postal code
Function collectionToArray(c As Collection) As Variant()
Dim a() As Variant: ReDim a(0 To c.Count - 1)
Dim i As Integer
For i = 1 To c.Count
a(i - 1) = c.Item(i)
Next
collectionToArray = a
End Function
Private Sub Worksheet_Change(ByVal Target As Range)
Dim row As Integer
Dim code As String
Dim villes As New Collection
Dim f As Worksheet
Dim cells As Range
Dim firstAddress
If Target.cells.Count = 1 And Target.cells(1, 1).Column = 7 Then
row = Target.cells(1, 1).row
code = Target.cells(1, 1).Text
If IsEmpty(Target.cells(1, 1)) Then
Range("H" & row).Validation.Delete
Else
With Worksheets(8).Range("A2:A50000")
Set c = .Find(code, LookIn:=xlValues)
If Not c Is Nothing Then
firstAddress = c.Address
Do
villes.Add c.Offset(0, 1).Text
Set c = .FindNext(c)
Loop While Not c Is Nothing And c.Address <> firstAddress
End If
End With
With Range("H" & row).Validation
.Delete
.Add Type:=xlValidateList, _
Formula1:=Join(collectionToArray(villes), ",")
End With
End If
End If
End Sub
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment