2016-07-29 146 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,如果它帮助你 –