VBA项目中的运行时错误

每当我运行这个代码时,我总是收到一个错误。 该错误是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_poscol来复制问题。在你的代码中,如果candidate < min从不为真,结果是s2_pos永远不会被设置。

我build议使用F8单步执行代码,以了解如何在数据中实现此scheme。

作为一个解决方法,在Do While r < 49之前将s2_pos = 0 ,然后将最后几行包装在下面的语句中。

 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 

下面的代码(我testing过)循环遍历第5到第48行(就像在你的代码中一样),并find(每行)最合适的电容(它们的值最接近于36)。 我对代码进行了一些修改,使其运行得更快,我认为更容易遵循。

下面的屏幕截图显示了我在Demo上得到的结果( 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