vba vba自动增加一个数字?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/26337568/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-08 09:01:49  来源:igfitidea点击:

vba auto increment a number?

excelvba

提问by liam spence

i am trying to insert a reference number into a cell in excel using vba. I want a prefix text of 'V0000' followed by an auto incremented number starting from 836.

我正在尝试使用 vba 在 excel 中的单元格中插入一个参考号。我想要一个“V0000”的前缀文本,后跟一个从 836 开始的自动递增数字。

so for each row that gets inserted I will have V0000836
Then V0000837
etc

A large portion of my code creates a new row and inserts data into it automatically one after the other, but instead of posting my whole code I am just wanting to focus on this one line of code which inserts value into column AA of my spreadsheet. I am using the following but it just gives me V00001 each time. can someone show me how I can get my code to do what I want it to.

我的大部分代码创建了一个新行并一个接一个地自动将数据插入其中,但我不想发布我的整个代码,我只想关注这一行将值插入到我的电子表格的 AA 列中的代码。我正在使用以下内容,但每次都只给我 V00001。有人可以告诉我如何让我的代码做我想要的。

ws2.Range("AA" & DestRow).Value = "V0000836" & Value + 1

回答by

Consider an alternative that does not remove numerical (mathematical) functionality from the cell's value.

考虑一个不从单元格的值中删除数字(数学)功能的替代方法。

ws2.Range("AA" & DestRow).numberformat = "\V0000000"
ws2.Range("AA" & DestRow).Value = 836 + 1

If you require the formatted (displayed) alphanumeric designation you can retrieve it like this.

如果您需要格式化(显示)的字母数字名称,您可以像这样检索它。

Dim str as string, num as long
str = ws2.Range("AA" & DestRow).text    '? V0000837
num = ws2.Range("AA" & DestRow).value   '? 837

回答by Gareth

Using VBA, you can do this by incrementing the number each time the loop goes round and then prefixing the V0000 to the front like so:

使用 VBA,您可以通过在每次循环时增加数字然后在前面添加 V0000 前缀来做到这一点,如下所示:

Dim i As Integer
Dim cell As Range, rng As Range

Set rng = Range("A1:A10")

i = 836

For Each cell In rng
    cell.Value = "V000" & i
    i = i + 1
Next cell