2014-06-30 247 views
0

我試圖設計一個函數,該函數搜索特定術語的第一行,然後在術語「Requirement」或「Function Change」中搜索該列。一旦找到這些術語,它將搜索包含這些術語的行,並在另一列中檢查術語「協議」。我試圖用Like操作符來完成這個任務,但我一直在彈出一個「應用程序定義或對象定義的錯誤」。任何人都可以弄清楚爲什麼我可能會得到這個錯誤?我一直在看它一段時間,無法弄清楚。下面的代碼我到目前爲止:在VBA中執行Like運算時出現運行時錯誤

編輯:錯誤時彈出的代碼獲取到第一IF語句

Function CountProtocol() As Long 

Sheets("CS-CRM Raw Data").Select 
Sheets("CS-CRM Raw Data").Unprotect 

    LastRow = Range("A" & Rows.Count).End(xlUp).row 
    LastColumn = Cells(1, Columns.Count).End(xlToLeft).Column 

    For i = 1 To LastRow 
     If Cells(i, myTypeCol).Value Like "Functional Change" Or "Requirement" Then 
      If Cells(i, myDescCol).Value Like "*protocol*" Then 
       pro_count = pro_count + 1 
      End If 
     End If 
    Next i 

    MsgBox "Requests of type ""Requirement"" or ""Functional Change"" that have ""Protocol"" in the description: " & pro_count 

CountProtocol = Pro 

End Function 

編輯:這裏是myTypeCol分配代碼:

Function ColSearch(Heading As String) As Integer 

Sheets("CS-CRM Raw Data").Select 
Sheets("CS-CRM Raw Data").Unprotect 

myCol = Sheets("CS-CRM Raw Data").Cells.Find(What:=Heading, LookAt:=xlWhole, SearchOrder:=xlByRows, SearchDirection:=xlNext, MatchCase:=False).Column 

ColSearch = myCol 

End Function 

這就是所謂的主子程序是這樣的:

myTypeCol = ColSearch("type") 
myDescCol = ColSearch("description") 

編輯:這是另外一個功能我哈這是調用myTypeCol,可以正常工作,沒有錯誤。

Function CountType() As Long 

Sheets("CS-CRM Raw Data").Select 
Sheets("CS-CRM Raw Data").Unprotect 

Dim type_count As Long 
Dim type_count2 As Long 
Dim type_sum As Long 

    LastRow = Range("A" & Rows.Count).End(xlUp).row 
    LastColumn = Cells(1, Columns.Count).End(xlToLeft).Column 

    type_count = Application.WorksheetFunction.CountIf(Range(myTypeCol & "2:" & myTypeCol & LastRow), "Requirement") 
    type_count2 = Application.WorksheetFunction.CountIf(Range(myTypeCol & "2:" & myTypeCol & LastRow), "Functional Change") 

    type_sum = type_count + type_count2 

    MsgBox "Requests of type ""Requirement"" or ""Functional Change"": " & type_sum 

CountType = Count 

End Function 

回答

2

您需要Or操作後對單元格的值進行比較,像這樣:

Function CountProtocol() As Long 

Sheets("CS-CRM Raw Data").Select 
Sheets("CS-CRM Raw Data").Unprotect 

    LastRow = Range("A" & Rows.Count).End(xlUp).row 
    LastColumn = Cells(1, Columns.Count).End(xlToLeft).Column 

    For i = 1 To LastRow 
     If Cells(i, myTypeCol).Value Like "Functional Change" Or Cells(i, myTypeCol).Value Like "Requirement" Then 
      If Cells(i, myDescCol).Value Like "*protocol*" Then 
       pro_count = pro_count + 1 
      End If 
     End If 
    Next i 

    MsgBox "Requests of type ""Requirement"" or ""Functional Change"" that have ""Protocol"" in the description: " & pro_count 

CountProtocol = Pro 

End Function 
+0

啊,好趕上。儘管如此,我仍然無法正常工作。當我進行上述建議的編輯時,我會在「Sheets(」CS-CRM Raw Data「)中得到一個」下標超出範圍錯誤「,選擇」line。如果我評論Sheets線,我會再次得到原始錯誤。「 – user3783788

+0

@ user3783788在哪裏分配了myTypeCol?如果它沒有被分配(看起來不是),那麼它的默認值是'0',這會引起1004的錯誤 –

+0

我有一個不同的函數, – user3783788