我試圖將我的列「C」設置爲等於一個範圍。我希望範圍爲0到MaxValue,增量爲0.1。所以它會像0,0.1,0.2,0.3 MaxValue一樣。當我使用這個代碼時,它只給了我整個列的一個值。怎麼會這樣呢?提前致謝!通過增加值來設置一個等於某個範圍的列
For p = 1 To MaxValue/0.1
For g = 0 To MaxValue
ws1.Cells(p + 9, "C") = g + 0.1
Next g
Next p
我試圖將我的列「C」設置爲等於一個範圍。我希望範圍爲0到MaxValue,增量爲0.1。所以它會像0,0.1,0.2,0.3 MaxValue一樣。當我使用這個代碼時,它只給了我整個列的一個值。怎麼會這樣呢?提前致謝!通過增加值來設置一個等於某個範圍的列
For p = 1 To MaxValue/0.1
For g = 0 To MaxValue
ws1.Cells(p + 9, "C") = g + 0.1
Next g
Next p
Sub test()
Dim intOffsetCounter As Integer
Dim dblMaxValue As Double
Dim dblCurrentValue As Double
dblMaxValue = 10
dblCurrentValue = 0
intOffsetCounter = 1
Do Until dblCurrentValue = dblMaxValue
If dblCurrentValue > dblMaxValue Then Exit Do
Sheets(1).Cells(intOffsetCounter, 3).Value = dblCurrentValue
dblCurrentValue = dblCurrentValue + 0.1
intOffsetCounter = intOffsetCounter + 1
Loop
End Sub
您可以改變的範圍內通過改變intOffsetCounter你想在開始任何行開始。
這將做到這一點,而無需過多修改代碼。
g = 0
For p = 1 To MaxValue/0.1
ws1.Cells(p + 9, "C") = g
g = g + 0.1
Next p
不會把這個g設置爲0每個循環? – ThatOneGuy
@ThatOneGuy - 謝謝。我在最後一秒把它放在了錯誤的地方。固定 –
這是一個簡單的While循環來做你正在尋找的東西。就在MaxValue的改變到你想要
Sub test()
Dim MaxValue As Double
Dim p, counter As Double
p = 0
counter = 1
MaxValue = 10
While p < MaxValue
Sheet1.Cells(counter, 3) = p
p = p + 0.1
counter = counter + 1
Wend
End Sub
2個選項是什麼:
Option Explicit
Public Sub SetFractions1()
Dim ws1 As Worksheet, r As Long, maxValue As Long
Set ws1 = ThisWorkbook.Worksheets("Sheet1")
maxValue = 33
For r = 0 To maxValue
ws1.Cells(r + 10, "C").Value2 = Format(r/10, "0.0")
Next
ws1.Range(ws1.Cells(10, "C"), ws1.Cells(Rows.Count, "C").End(xlUp)).NumberFormat = "0.0"
End Sub
Public Sub SetFractions2()
Dim ws1 As Worksheet, maxValue As Long
Set ws1 = ThisWorkbook.Worksheets("Sheet1")
maxValue = 33
If maxValue > 9 Then
With ws1.Range(ws1.Cells(10, "C"), ws1.Cells(maxValue + 10, "C"))
.Formula = "= (Row() - 10)/10"
.NumberFormat = "#,##0.0"
End With
End If
End Sub
運行調試器可能會揭示爲什麼這個代碼不工作。 'p'的外部循環控制着哪個單元被訪問。 'g'的內部循環控制輸出的值。不幸的是,每個'p'的值將從'g'循環中的最後一次迭代開始,因爲所有的輸出都會轉到單個單元。另外,根據'MaxValue'的值,可能會得到非整數行數,這可能會導致問題。斯科特的答案是解決這個循環問題的最乾淨的解決方案。 –