简体   繁体   中英

Visual Basic Excel For Loop In Multiple Cells How To Use The Counter In The Range(“”)

This is what I have, so the H needs to be followed by the number of the cell, I want to use the counter i here, but it doesn't work. What am I doing wrong? :)

For i = 60 To 63

    Range("Hi").AddComment
    Range("Hi").Comment.Visible = False
    Range("Hi").Comment.Text Text:=""
    i = i + 1
    Range("Hi").Select
    i = i - 1
    Next
End Sub

Use this:

Range("H" & i)

As you wrote it, "Hi" does not use the variable i because you put it in quotes.

You need to do this instead:

For i = 60 To 63

    Range("H" & i).AddComment
    Range("H" & i).Comment.Visible = False
    Range("H" & i).Comment.Text Text:=""
    i = i + 1
    Range("H" & i).Select
    i = i - 1
    Next
End Sub

The & operator does concatenation in VBA.

You should format it like this:

    For i = 60 To 63

        Range("H" & i).AddComment
        Range("H" & i).Comment.Visible = False
        Range("H" & i).Comment.Text Text:=""
        i = i + 1
        Range("H" & i).Select
        i = i - 1
    Next i
End Sub

The reason is that the letter H is a character and i is a variable. anything inside of double quotes "Hi" like that Excel will read as just a string of text.

When Excel reads a word or letter outside of quotes i it will assume it is a variable. The & character joins the two together as text.

This means that each time the loop runs Excel will read it as "H" and i and translate it to "H1", "H2", "H3", .... "H60" and input it into the Range() like you are looking for.

Would this work better for you? I've always had issues when the value of i starts chaging inside the loop code

For i = 60 To 63      
    With Range("H" & i)
        .Select 
        .AddComment     
        .Comment.Visible = False     
        .Comment.Text Text:=""  
    end with
Next 
End Sub 

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