2013-08-06 40 views
0

我對VBA相當陌生。我試圖寫一個程序,通過大量的各種格式的零件號的運行和分類等零件編號,像這樣:爲什麼我得到運行時錯誤424對象是否需要?

12A3-4 
1B-4 
2B-6 
A12B 

再有我的計劃找到這些類型的所有格式,並返回和算來,像這樣:(現注號碼由#代表)

##A# 1 
    #B 2 
    A##B 1 

但我得到的是我似乎無法源的運行時錯誤。

我的程序如下。可能還有其他錯誤。

Sub CheckPartNumbers() 

' Select cell A2, where data begins 
Range("A2").Select 
' Declare variable for cell location of our output 
Dim Cell As Range 
Set Cell = ActiveSheet.Range("C2") 

' Set Do loop to stop when an empty cell is reached. 
Do Until IsEmpty(ActiveCell) 
' Initialize vairable of type string to "" 
Dim partsFormat As String 
partsFormat = "" 
' Run through each character of row 
For i = 1 To Len(ActiveCell.Value) 
    Dim thisChar As String 
    thisChar = Mid(ActiveCell.Value, i, 1) 
    ' if thisChar is a letter 
    If IsLetter(thisChar) Then 
    partsFormat = partsFormat & thisChar 
    ' if thischar is a number 
    ElseIf IsNumeric(thisChar) Then 
    partsFormat = partsFormat & "#" 
    ' if dash 
    ElseIf thisChar = "-" And (Len(ActiveCell.Value) - Len(Replace(ActiveCell.Value, "-", ""))) > 1 Then 
    partsFormat = partsFormat & thisChar 
    Else 
    i = Len(ActiveCell.Value) 
    End If 
Next i 
' Check if partsFormat already exists in results with Match 
Dim myLocation As Range 
Set myLocation = Application.Match(partsFormat, Range("C2:D1")) 
' If no, result will give error, so add partsFormat and make count 1 
If IsError(myLocation) Then 
Range(Cell) = partsFormat 
Range(Cell).Offset(0, 1) = 1 
Cell = Cell.Offset(1, 0) 
' If yes, add 1 to appropriate cell 
Else 
myLocation.Offset(0, 1) = myLocation.Offset(0, 1).Value + 1 
End If 

' Run through next row 
ActiveCell.Offset(1, 0).Select 
Loop 

End Sub 

任何幫助表示讚賞!

編輯: 我有不少錯誤,所以這一塊我的代碼更新:

Dim myLocation As Variant 
myLocation = Application.Match(partsFormat, Range("C1").EntireColumn) 
' If no, result will give error, so add partsFormat and make count 1 
If IsError(myLocation) Then 
Cell = partsFormat 
Cell.Offset(0, 1) = 1 
Cell = Cell.Offset(1, 0) 
' If yes, add 1 to appropriate cell 
Else 
'myLocation.Offset(0, 1) = myLocation.Offset(0, 1).Value + 1 
End If 
+1

您是否已經使用調試器? http://krgreenlee.blogspot.nl/2006/04/programming-excel-vba-debugging-for.html – rene

+0

請包括您收到的運行時錯誤,並在可能的情況下包含發生什麼問題。 – sigil

+0

我一直在調試,雖然我的錯誤永遠不會突出顯示一行,但我確定使用Match函數開始「Set myLocation」的行是罪魁禍首。我只是不知道爲什麼。正如我在標題中所述,錯誤是運行時錯誤424. – user2657997

回答

3

的424錯誤是由以下兩行造成的:

Dim myLocation As Range 
Set myLocation = Application.Match(partsFormat, Range("C2:D1")) 

您已經將myLocation聲明爲Range。然後,您嘗試將其設置爲一個數字,這是MATCH返回的值,而不是範圍。所需的對象是一個範圍。

編輯:

爲了算了算的partsFormat在C欄的出現,使用這樣的:

Dim partsFormat As String 
Dim partsFormatCount As Long 

partsFormat = "Part" 
partsFormatCount = Application.WorksheetFunction.CountIf(Range("C:C"), partsFormat) 

你顯然需要插入到代碼中的正確的地方。

+0

我認爲這是位置...我怎樣才能使用函數來給我一個範圍值? – user2657997

+0

另外,謝謝 – user2657997

+0

範圍值在哪一列?此外,我只是注意到,你正在嘗試匹配多個列或行,這是行不通的。我認爲你需要更好地描述你的目標。 –

相關問題