Excel VBA For-Loop只能在debugging模式下运行

我想弄清楚为什么下面的代码只能在debugging模式下工作…

当我点击“保存”button时,即使是同一公司名称,macros也会保存每个数据条目。 当我debuggingmacros进入for循环,并给我的消息“公司已经存在”。

我的错误在哪里?

Sub Copy_Values() Dim sapcolleague As String, str1 As String, str2 As String, str3 As String Dim i As Integer, ValueToFind As String, ValueToCheck As String Dim totalAccRows As Integer Dim accColumn As Integer Dim currentAccRow As Integer accColumn = 2 totalAccRows = Worksheets("DB").Cells(Rows.Count, accColumn).End(xlUp).Row ValueToFind = Worksheets("Maintain").Range("F13").Value For currentAccRow = 2 To totalAccRows If Cells(currentAccRow, accColumn).Value = ValueToFind Then MsgBox ("Company already exists!") Exit Sub End If Next Worksheets("DB").Range("A8").EntireRow.Insert Worksheets("DB").Range("A8").Value = Worksheets("Maintain").Range("F11").Value Worksheets("DB").Range("B8").Value = Worksheets("Maintain").Range("F13").Value Worksheets("DB").Range("C8").Value = Worksheets("Maintain").Range("F15").Value str1 = Worksheets("Maintain").Range("F18").Value str2 = Worksheets("Maintain").Range("F19").Value str3 = Worksheets("Maintain").Range("F20").Value sapcolleague = str1 & " " & str2 & " " & str3 Worksheets("DB").Range("D8").Value = sapcolleague ' This MsgBox will only show if the loop completes with no success MsgBox "Successfully saved!" End Sub 

If Cells(currentAccRow, accColumn).Value = ValueToFind Then Cells没有父工作表,所以它将在运行时成为ActiveSheet。

快速重写:

 Option Explicit Sub Copy_Values() Dim sapcolleague As String, valueToFind As String, accColumn As Long With Worksheets("DB") accColumn = 2 valueToFind = Worksheets("Maintain").Range("F13").Value If Not IsError(Application.Match(valueToFind, .Columns(accColumn), 0)) Then MsgBox ("Company already exists!") Exit Sub End If .Range("A8").EntireRow.Insert .Range("A8:C8").Value = Array(Worksheets("Maintain").Range("F11").Value, _ valueToFind, _ Worksheets("Maintain").Range("F15").Value) sapcolleague = Join(Array(Worksheets("Maintain").Range("F18").Value, _ Worksheets("Maintain").Range("F19").Value, _ Worksheets("Maintain").Range("F20").Value), Chr(32)) .Range("D8").Value = sapcolleague End With 'Shouldn't it be saved somewhere around here? ' This MsgBox will only show if the loop completes with no success MsgBox "Successfully saved!" End Sub