简体   繁体   中英

Excel VBA Looping through cells and replacing their values

I am trying to build a macro that cycles through a column of cells and replaces a two letter country code in that cell with the name of that country. However I get an object not found error when I try to run the macro.

Sub ChangeCountryText()
'
' ChangeCountryText Macro
' Changes country codes
'
    For counter = 2 To 20
        Set curCell = ActiveSheet.Cells(counter, 1)
        Select Case curCell.Text
            Case "JP"
                curCell.Text = "Japan"
            Case "FR"
                curCell.Text = "France"
            Case "IT"
                curCell.Text = "Italy"
            Case "US"
                curCell.Text = "United States"
            Case "NL"
                curCell.Text = "Netherlands"
            Case "CH"
                curCell.Text = "Switzerland"
            Case "CA"
                curCell.Text = "Canada"
            Case "CN"
                curCell.Text = "China"
            Case "IN"
                curCell.Text = "India"
            Case "SG"
                curCell.Text = "Singapore"
        End Select
    Next counter

End Sub

The Text property is read-only - you can't set it. Assign to the Value property and it should work (eg curCell.Value = "Japan" )

我确定您有充分的理由为此使用宏,但是您可能希望研究LOOKUP或VLOOKUP工作表函数,以作为无需编写宏即可执行此类操作的一种方式。

You should be able to enter the debugger by clicking to the left of your macro text in the editor and placing a red dot on the line

For counter = 2 To 20

Then you can step through your macro until you get to the error.

Alternatively you can add error handling to your macro

On Error Goto Failed

at the top and before the end sub add

Failed: 
'handle error here

"Object not found" is likely from the curCell.Text call (curCell is null, nothing, or invalid, so calling .Text on it is failing) or the ActiveSheet.Cells call (not sure if this can happen)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM