[英]Why am I getting “run-time error '424': object required” using VBA in Excel?
[英]Why am I getting Run-time Error 424 Object Required?
我是VBA的新手。 我試圖編寫一個程序來運行大量各種格式的零件號,並對這些零件號進行分類,如下所示:
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
424錯誤是由以下兩行引起的:
Dim myLocation As Range
Set myLocation = Application.Match(partsFormat, Range("C2:D1"))
您已將myLocation聲明為Range
。 然后,您嘗試將其設置為MATCH
返回的數字,而不是Range。 所需的對象是一個范圍。
編輯:
為了只計算C列中partsFormat
的出現,請使用類似以下內容的方法:
Dim partsFormat As String
Dim partsFormatCount As Long
partsFormat = "Part"
partsFormatCount = Application.WorksheetFunction.CountIf(Range("C:C"), partsFormat)
顯然,您必須將其插入代碼中的正確位置。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.