[英]How to increment decimal values in cell in excel VBA
我正在學習 VBA 編碼,需要一些幫助來編寫一個循環來增加單元格並按十進制值增加單元格內容。
在互聯網上搜索並找到了一個 do while 循環代碼,它只增加數字,不能增加十進制值
Sub Doeg()
Dim counter As Double
counter = 1
Do While counter < 10
Cells(counter, "A"). Value = counter
counter = counter + 1
Loop
End Sub
上面的代碼將單元格和每個單元格的值增加1
。 我想從1.2
開始,並將每個單元格的值增加0.1
以獲得十個值
你可以這樣做。 在這種情況下, For-Next
似乎是更好的選擇。
Sub Doeg()
Dim counter As Long
For counter = 1 To 10
Cells(counter, "A").Value = (counter - 1) * 0.1 + 1.2
Next counter
End Sub
不需要循環。
Sub Doeg()
With ActiveSheet.Range("A1:A10")
.Formula = "=(ROW()-1)*.01+1.2"
.Value = .Value
End With
End Sub
如果你想要一個循環,我會練習循環變量數組而不是范圍:
Sub Doeg()
Dim otArr(1 to 10, 1 to 1) as Variant
Dim i as Long
For i = LBound(otArr,1) to UBound(otArr,1)
otArr(i,1) = (i - 1) * 0.1 + 1.2
Next i
ActiveSheet.Range("A1").Resize(UBound(otArr,1),UBound(otArr,2)).Value = otArr
End Sub
雖然在這個特定的例子中完成的時間不會有明顯的不同,但如果你有 1000 甚至 100,000,那么時間就會變得明顯。
但是對於 SJR 在上述評論中的建議。
將counter = 1
更改為counter = 1.2
將Do While counter < 10
更改為Do While counter < 10 * 0.1 + 1.2
並將counter = counter + 1
更改為counter = counter + 0.1
您可以使用此代碼:
Sub Doeg()
Dim counter As Double
counter = 1.1
Do While counter < 10
Cells(counter, "A").Value = counter
counter = counter + 1.1
counter = counter - 0.1
Loop
End Sub
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.