[英]Runtime Error in VBA Project
每當我運行此代碼時,我總是收到錯誤消息。 該錯誤是1004運行時錯誤。 請幫助我弄清楚我的代碼出了什么問題。 我對VBA完全陌生,但我確實知道如何使用Python和C。
Option Explicit
Sub Experiment()
Dim m1 As Worksheet
Set m1 = ThisWorkbook.Worksheets("Sheet1")
Dim col As Integer
Dim row As Integer
Dim initial As Double
Dim s1 As Double
Dim s1_pos As Integer
Dim s2 As Double
Dim s2_pos As Integer
Dim min As Double
Dim candidate As Double
Dim temp_swap As Double
Dim r As Integer
col = 2
'For col = 2 To 18 Step 3
For row = 5 To 47 Step 2
initial = m1.Cells(row, col).Value
s1 = m1.Cells(row + 1, col).Value
s1_pos = row + 1
min = Abs(36 - (initial + s1))
r = row + 1
Do While r < 49
s2 = m1.Cells(r, col).Value
candidate = Abs(36 - (initial + s2))
If candidate < min Then
min = candidate
s2_pos = r
End If
r = r + 1
Loop
temp_swap = s1
m1.Cells(s1_pos, col).Value = s2
m1.Cells(s2_pos, col).Value = temp_swap
Next row
End Sub
我可以通過將s2_pos
或col
設置為0來復制問題。在您的代碼中,如果candidate < min
從未為真,則將發生此情況,因為結果是s2_pos
從未設置。
我建議您使用F8單步執行代碼,以了解如何在數據中獲得這種情況。
解決方法是,將s2_pos = 0
放在Do While r < 49
,然后在下面的is語句中包裝最后幾行。
If s2_pos <> 0 then
temp_swap = s1
m1.Cells(s1_pos, col).Value = s2
m1.Cells(s2_pos, col).Value = temp_swap
End If
下面的代碼(我測試過)循環遍歷第5到48行(就像您的代碼一樣),並(每行)找到最合適的電容器(它們的值最接近36)。 我對代碼進行了一些修改,以使其運行更快,並且我認為您更容易理解。
下面的屏幕截圖顯示了我在演示中得到的結果( C列獲得了最匹配的電容器的行號, D列顯示了該電容器的值)
這是代碼:
Option Explicit
Sub Experiment()
Dim m1 As Worksheet
Set m1 = ThisWorkbook.Worksheets("Sheet1")
Dim col As Integer
Dim row As Integer
Dim i As Integer
Dim Capacitor_Val As Double
Dim Current_Rng As Range
Dim Row_Found As Long
Dim Minimum_Gap As Double
col = 2
For row = 5 To 47
' just a high value to reset this flag
Minimum_Gap = 3
For i = row + 1 To 48
If Abs(36 - (m1.Cells(i, col) + m1.Cells(row, col))) < Minimum_Gap Then
Minimum_Gap = Abs(36 - (m1.Cells(i, col) + m1.Cells(row, col)))
Row_Found = i
Capacitor_Val = m1.Cells(i, col)
End If
Next i
m1.Cells(row, col + 1).Value = Row_Found
m1.Cells(row, col + 2).Value = Capacitor_Val
Next row
End Sub
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.