This is my first time ever working with VBA and Excel and my problem is probably caused by a big lack of knowledge on my part.
I have a one column list of city names (containing 800 items, hence I'm looking to automatically replace them) and some chunks of text in which the term "cityname" occurs multiple times and needs to be replaced by the correct city name, which in my setup would be the value of the first column cell in the same row.
So I found this: How to iterate through all the cells in Excel VBA or VSTO 2005
and found the InStr and Substitute functions by looking through the Excel VBA reference.
Using the iteration like this works fine:
Sub MySubstitute()
Dim cell As Range
For Each cell In ActiveSheet.UsedRange.Cells
If InStr(cell.Value, "cityname") > 0 Then
MsgBox "Hello World!"
End If
Next cell
End Sub
I get a message box for every "cityname" in my sheet (a test sheet with only 2 rows).
However when I add what I really want to achieve I get a Runtime Error (1004):
Sub MySubstitute()
Dim cell As Range
For Each cell In ActiveSheet.UsedRange.Cells
If InStr(cell.Value, "cityname") > 0 Then
cell.Value = WorksheetFunction.Substitute(cell.Value, "cityname", Cells(cell.Row, A))
End If
Next cell
End Sub
So I guess something in that line is wrong but I can't figure out what. Any hints to what my mistake is are appreciated, thanks :)