首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >为什么我得到运行时错误424对象需要?

为什么我得到运行时错误424对象需要?
EN

Stack Overflow用户
提问于 2013-08-07 02:39:46
回答 1查看 41.5K关注 0票数 0

我是VBA的新手。我正在尝试编写一个程序来运行各种格式的大量零件号,并对这些零件号进行分类,如下所示:

代码语言:javascript
复制
12A3-4
1B-4
2B-6
A12B

然后让我的程序找到这些类型的所有格式,并返回并计算它们,如下所示:(注意数字现在用#表示)

代码语言:javascript
复制
    ##A# 1
    #B 2
    A##B 1

但我得到了一个运行时错误,我似乎无法找到来源。

我的程序如下所示。可能还有其他错误。

代码语言:javascript
复制
 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

如有任何帮助,我们不胜感激!

编辑:我有相当多的错误,所以我的代码块被更新了:

代码语言:javascript
复制
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
EN

回答 1

Stack Overflow用户

发布于 2013-08-07 03:18:16

424错误是由以下两行引起的:

代码语言:javascript
复制
Dim myLocation As Range
Set myLocation = Application.Match(partsFormat, Range("C2:D1"))

您已将myLocation声明为Range。然后,您尝试将其设置为一个数字,这是MATCH返回的结果,而不是一个范围。需要的对象是一个范围。

编辑:

为了只计算C列中partsFormat的出现次数,可以使用如下代码:

代码语言:javascript
复制
Dim partsFormat As String
Dim partsFormatCount As Long

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

显然,您必须将其插入到代码中的正确位置。

票数 3
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/18088009

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档