Excel VBA iterate over all used cells and substitute their values

老子叫甜甜 提交于 2020-01-07 02:35:07

问题


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 :)


回答1:


You should change:

 cell.Value = WorksheetFunction.Substitute(cell.Value, "cityname", Cells(cell.Row, A))

by

 cell.Value = WorksheetFunction.Substitute(cell.Value, "cityname", Cells(cell.Row, 1))



回答2:


You can use the Range.Replace Method and replace all at once no need to iterate.

Sub MySubstitute()
    Dim rng As Range
    Set rng = ActiveSheet.UsedRange.Cells
    rng.Replace "cityname", "correctcityname", xlPart
End Sub


来源:https://stackoverflow.com/questions/35066409/excel-vba-iterate-over-all-used-cells-and-substitute-their-values

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!