简体   繁体   English

Visual Basic Excel For多个单元格中的循环如何使用范围内的计数器(“”)

[英]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. 这就是我所拥有的,因此H后面必须跟单元格的编号,我想在这里使用计数器i,但它不起作用。 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. 在您编写时, "Hi"不使用变量i,因为您将其放在了引号中。

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. &运算符在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. 原因是字母H是一个字符,而i是一个变量。 anything inside of double quotes "Hi" like that Excel will read as just a string of text. 像Excel这样的双引号"Hi"任何内容都将读为一串文本。

When Excel reads a word or letter outside of quotes i it will assume it is a variable. 当Excel读取引号之外的单词或字母i ,它将假定它是一个变量。 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. 这意味着每次循环运行时,Excel都将其读取为"H" and i ,并将其转换为“ H1”,“ H2”,“ H3”,...。“ H60”,并将其输入到Range()就像您正在寻找。

Would this work better for you? 这样对您会更好吗? I've always had issues when the value of i starts chaging inside the loop code 当i的值开始进入循环代码时,我总是遇到问题

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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