Forum Discussion
Niklas Kalz
Oct 08, 2017Copper Contributor
String-Variables should be changed to numbers
Hello, I would like to change an address list of "surnames, names"(strings) ---> to numbers: Lehmann, Arthur ---> changed to ---> 1 Lehmann, Arthur ---> changed to --->1 Lehmann, Arthur --->...
- Oct 09, 2017
Hi,
You could use something like the below code. Call it like StringsToNumbers(Range("A2:A10"), Range("B2:B10"))
Sub StringsToNumbers( _ ByVal StringRange As Range, _ ByVal OutputRange As Range, _ Optional ByVal StartingNumber As Long = 1 _ ) Dim Names As New Collection Dim Index As Long Dim Row As Long Dim Column As Long If StringRange.Cells.Count <> OutputRange.Cells.Count Or StringRange.Areas.Count <> OutputRange.Areas.Count Then Exit Sub Index = 1 For Row = 1 To StringRange.Rows.Count For Column = 1 To StringRange.Columns.Count If Not InCollection(Names, StringRange(Row, Column).Value2) Then Names.Add Index, StringRange(Row, Column).Value2 OutputRange(Row, Column).Value2 = Index Index = Index + 1 Else OutputRange(Row, Column) = Names.Item(CStr(StringRange(Row, Column))) End If Next Column Next Row End Sub
Zack Barresse
Oct 09, 2017Iron Contributor
Hi,
You could use something like the below code. Call it like StringsToNumbers(Range("A2:A10"), Range("B2:B10"))
Sub StringsToNumbers( _
ByVal StringRange As Range, _
ByVal OutputRange As Range, _
Optional ByVal StartingNumber As Long = 1 _
)
Dim Names As New Collection
Dim Index As Long
Dim Row As Long
Dim Column As Long
If StringRange.Cells.Count <> OutputRange.Cells.Count Or StringRange.Areas.Count <> OutputRange.Areas.Count Then Exit Sub
Index = 1
For Row = 1 To StringRange.Rows.Count
For Column = 1 To StringRange.Columns.Count
If Not InCollection(Names, StringRange(Row, Column).Value2) Then
Names.Add Index, StringRange(Row, Column).Value2
OutputRange(Row, Column).Value2 = Index
Index = Index + 1
Else
OutputRange(Row, Column) = Names.Item(CStr(StringRange(Row, Column)))
End If
Next Column
Next Row
End Sub
Niklas Kalz
Oct 10, 2017Copper Contributor
Many thanks for your detailed answer which is really useful!!
Niklas
Niklas