2016-07-29 134 views
0

每當我運行此代碼時,我總是收到錯誤。該錯誤是1004運行時錯誤。請幫我弄清楚我的代碼出錯了。我完全新的VBA,但我不知道如何使用Python和C.VBA項目中的運行時錯誤

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 
+0

請指定@哪一行錯誤被拋出?如果你可以分享excel表單圖片,那會很棒 – Siva

+0

@Kurst你想達到什麼效果?因爲你的'While'循環似乎並不理想,你是否在尋找一個取決於動態範圍的最小值?在這種情況下,你可以使用'匹配'與'Min' –

+0

@Siva m1.Cells(s2_pos,col).Value = temp_swap,對不起,代碼段工具不工作:'( – Kurst

回答

1

我能夠通過設置任何s2_poscol爲0。在你的代碼複製的問題,如果candidate < min從來沒有這會發生真的,因爲s2_pos永遠不會被設置。

我建議使用F8單步執行代碼,以瞭解如何在數據中實現此場景。

作爲解決方法,將s2_pos = 0放置在Do While r < 49之前,然後將最後幾行包裝在下面的語句中。

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 
+0

感謝您的反饋Gary! :) – Kurst

0

下面的代碼(我測試),遍歷行5〜48(如在您的代碼),並發現(每行)的最合適的電容器(它們一起具有值最接近於36)。 我對代碼進行了一些修改,使其運行速度更快,並且我認爲您更容易遵循。

下面的屏幕截圖顯示我在我的演示得到了結果(列C得到與最佳匹配電容器的行數,列d顯示,電容值) enter image description here

這裏是代碼:

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 
+0

嘿嘿,非常感謝你的跟進。它真的幫助:) – Kurst

+0

@Kurst你歡迎,隨時upvote,如果它幫助你 –