VBA - 尝试将递增数字添加到 Excel 单元格
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/25889021/
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
VBA - Trying to add incrementing numbers to an excel cell
提问by Pat
Sorry, new to VBA and I cant find the answer I need (several close ones though)
对不起,VBA 新手,我找不到我需要的答案(虽然有几个接近的)
I have Col B in a worksheet and its got content to from B1 downwards (B4 in this example). The number of the last filled cell will be different each time - B4 now in this example, B5 tomorrow, B20 next week.
我在工作表中有 Col B,它的内容从 B1 向下(在本例中为 B4)。最后填充的单元格的编号每次都会不同 - 在此示例中现在为 B4,明天为 B5,下周为 B20。
I want to fill Col A with a number for each cell where B has a value – basically an ID number The number doesn't start at 1 & will be different each time. The number in A1 comes from a cell in another sheet – I just copy it to A1 and I want then to use that as the starting point. The number will then increment as it progresses down. Example:
我想为每个单元格填充一个数字,其中 B 有一个值——基本上是一个 ID 号。数字不是从 1 开始的,每次都会不同。A1 中的数字来自另一张工作表中的一个单元格——我只是将它复制到 A1,然后我想将其用作起点。然后,该数字将随着它的下降而增加。例子:
ColA ColB
可乐
508 -- blab blab
第508章--
509 -- yada yada
509——亚达亚达
510 -- etc etc
510 -- 等等
511 -- whatever
511——随便
in my code, this fills the cols but just with the value from A1
在我的代码中,这会填充列,但只是使用 A1 中的值
Dim lastRow As Long
lastRow = Range("B" & Rows.Count).End(xlUp).Row
Range("A1").AutoFill Destination:=Range("A1:A" & lastRow)
I tried to add the Row number to the value of A1 and then take away one (so for row 2 = 2+508-1 = 509)
我试图将行号添加到 A1 的值,然后拿走一个(所以对于第 2 行 = 2+508-1 = 509)
Range("A2:A" & lastRow).Formula = "=ROW()+A1-1"
BUT when run, the A1 becomes A2 and in the next row its A3 etc so the numbers are out of wack
但是当运行时,A1 变成 A2,在下一行是 A3 等,所以数字不正常
I tried a few other things and always its not working right; close but no cigar. I've been searching for examples and everything I find is close but not enough.
我尝试了其他一些事情,但总是无法正常工作;关闭但没有雪茄。我一直在寻找例子,我发现的一切都很接近但还不够。
Q: is there are way to keep the A1 as A1 while this populates the range OR is there another way of doing this?
问:有没有办法在填充范围时将 A1 保持为 A1,或者有另一种方法吗?
Many Thanks
非常感谢
回答by Gary's Student
Manually place the value in A1as before, then in A2enter:
像以前一样手动将值放在A1中,然后在A2 中输入:
=IF(B2="","",A1+1)
and copy down (no VBA needed)
并复制下来(不需要 VBA)
EDIT#1:
编辑#1:
If VBAis a requirement then:
如果需要VBA,则:
Sub dural()
Dim lastRow As Long
lastRow = Range("B" & Rows.Count).End(xlUp).Row
Range("A1").AutoFill Destination:=Range("A1:A" & lastRow), Type:=xlFillSeries
End Sub