2017-03-24 107 views
0

所以,我在此行中得到一個錯誤:Excel的VBA錯誤越來越oppStatLoc

If Sheets(2).Cells(j, oppStatLoc).Value = OppStat Then  

程序運行,但再經過它達到一定行停止和滯後。然後錯誤1004彈出。這是代碼。

代碼:

Function getOppStat(OppStat As String) 
     'For testing Purposes 
     Dim paramList 
     Dim lastRow As Long, lastCol As Long, currentRow As Long, oppStatLoc As Long 

     lastRow = Sheets("Parameter").Range("A65536").End(xlUp).Row 
     lastCol = Sheets("Parameter").Range("XFD3").End(xlToLeft).Column 
     currentRow = 2 'Sheets("OppStat").Range("A65536").End(xlUp).Row + 1 

     'Set Up Headerz 
     For i = 1 To lastCol 
      Sheets("Parameter").Cells(3, i).Copy _ 
       Destination:=Sheets("OppStat").Cells(1, i) 
     Next i 

     'Look for OppStat Column 
     For i = 1 To lastCol 
      If Sheets("Parameter").Cells(3, i).Value = "Opportunity Status" Then 
       oppStatLoc = i 
      End If 
     Next i 

     'Set Up Valuez 
     For j = 4 To lastRow 
      If Sheets(2).Cells(j, oppStatLoc).Value = OppStat Then 
       For k = 1 To lastCol 
        Sheets(2).Cells(j, k).Copy _ 
         Destination:=Sheets(3).Cells(currentRow, k) 
       Next k 
       currentRow = currentRow + 1 
      End If 

     Next j 

    End Function 

可能是什麼問題呢? lastRow的值是4213.

+1

在oppStatLoc變量上添加一個手錶,看看它是否返回可接受的結果。如果沒有找到「Opportunity Status」,它不會等於0。考慮到你正在使用函數,你也不會在'getOppStat'中返回任何值。如果您不需要返回值,請使用「Sub」過程。 – L42

+0

你是什麼意思添加一個手錶男人?你可以發佈代碼嗎?不熟悉所有的方法和功能。 – nubcoder17

+0

它位於* VBE編輯器*上的'Debug'選項卡下。你用它來監視某個變量的值。或者你可以在你的第二個'For'循環之後簡單地添加這行。 'Debug.Print oppStatLoc'。這將在您的直接窗口中打印變量的值。要查看*立即窗口*,請按** CTRL + G **。 – L42

回答

0

如果我> lastCol會發生什麼?我建議如下構建你的循環。

For i = lastCol to 1 step -1 
    If Sheets("Parameter").Cells(3, i).Value = "Opportunity Status" Then 
     oppStatLoc = I 
     exit for 
    End If 
Next i 

如果找不到匹配,此循環將設置I = 0。你應該添加一個測試,如If i Then,並確定它做了什麼它失敗(意思是我= 0)