我對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
您是否已經使用調試器? http://krgreenlee.blogspot.nl/2006/04/programming-excel-vba-debugging-for.html – rene
請包括您收到的運行時錯誤,並在可能的情況下包含發生什麼問題。 – sigil
我一直在調試,雖然我的錯誤永遠不會突出顯示一行,但我確定使用Match函數開始「Set myLocation」的行是罪魁禍首。我只是不知道爲什麼。正如我在標題中所述,錯誤是運行時錯誤424. – user2657997