VBA项目中的运行时错误

时间:2016-07-29 05:35:45

标签: excel vba excel-vba runtime-error

每当我运行此代码时,我都会收到错误消息。该错误是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

2 个答案:

答案 0 :(得分:1)

我能够通过将s2_poscol设置为0来复制该问题。在您的代码中,如果candidate < min永远不为真,则会发生这种情况,因为结果是{ {1}}永远不会被设置。

我建议您使用F8逐步完成代码,以了解如何在数据中使用此方案。

作为一种解决方法,请在s2_pos之前放置s2_pos = 0,然后在下面的语句中包含最后几行。

Do While r < 49

答案 1 :(得分: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