2017-04-11 74 views
2

我試圖找出爲什麼下面的代碼僅在調試模式下工作......Excel VBA中的for循環僅在調試模式下運行

當我打我的「保存」按鈕宏觀節省每數據錄入甚至如果它是相同的公司名稱。當我調試宏進入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 
+0

什麼是保存和這個宏之間的聯繫? – sktneer

+2

'如果單元格(currentAccRow,accColumn).Value = ValueToFind Then'這裏單元格將引用哪個表單碰巧是活動表單。最好限定每個使用範圍/單元格的工作表對象。調試時,您可能選擇了不同的工作表。使用'If Worksheets(「DB」)。Cells(currentAccRow,accColumn).Value = ValueToFind Then' –

+0

偉大的提示!我沒有確定參考正確的工作表。你的提案奏效了! 非常感謝! –

回答

1

If Cells(currentAccRow, accColumn).Value = ValueToFind ThenCells沒有父表,因此將是在運行時的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 
+0

「保存」可能指的是複製「維護」表單中的信息並將其「保存」到「數據庫」表單中。 – YowE3K