所有
我收到错误"应用程序定义或对象定义错误"对于我写过的私人子。代码如下:
Private Sub CommandButton3_Click()
Dim MyLastRow As Long
Dim i As Long
Dim cellmatch
'Find the last row
MyLastRow = Cells(Rows.Count, "A").End(xlUp).Row
'Define our comparison
cellmatch = Application.Match(Cells(i, "A").Value, Range(Cells(i, "C")).Value, 0)
'Compare Raw Data cell to Stock column and find a match
For i = 2 To MyLastRow
If IsError(cellmatch) Then
Cells(i, 2) = "Not in Stock"
Else
Cells(i, 2) = "-"
End If
Next i
End Sub
我已尝试过在论坛上找到的一些内容,例如我们指定工作表
Application.WorksheetFuncion.Match.....
我也试过指向细胞或范围,例如:
Range(.Cells(i,"C"))....
或 .Match(.Cells(I," A&#34))...
但我一直得到同样的错误。所有这一切都发生在同一张纸上,而我并没有尝试做任何像复制一样的事情。我只是询问是否找不到匹配,然后标记为这样,否则,用短划线标记(为清楚起见,这样做)。我确信它非常简单,但我不熟悉VBA编码。非常感谢任何帮助。
谢谢!
答案 0 :(得分:1)
您的代码需要更改此代码行。
cellmatch = Application.Match(Cells(i, "A").Value, Range(Cells(i, "C")).Value, 0)
以强>
'Adjust Sheetname as per your requirements instead of "Sheet1"
cellmatch = Application.Match(Cells(i, "A").Value, Worksheets("Sheet1").Columns(3), 0)
修改强>
由于以下代码片段,您的程序中会出现主要问题。
Range(Cells(i, "C")).Value
如果我们参考MSDN文档 Range.Cells Property (Excel)
它提到了正确使用语法的例子。 典型的例子是
Set r = Range("myRange")
For n = 1 To r.Rows.Count
If r.Cells(n, 1) = r.Cells(n + 1, 1) Then
MsgBox "Duplicate data in " & r.Cells(n + 1, 1).Address
End If
Next n
因此它转换为Range("myRange").Cells(n,1)
而不是
Range(Cells(i, "C"))
它将给出正确的结果,如快照中所示。
答案 1 :(得分:0)
我相信这就是你要找的东西:
Option Explicit
Private Sub CommandButton3_Click()
Dim lngRow As Long
Dim rngFound As Range
Dim lngLastRow As Long
Dim shtCurrent As Worksheet
'Set the sheet to work on
Set shtCurrent = ThisWorkbook.Worksheets("Sheet1")
With shtCurrent
'Find the last row
lngLastRow = .Cells(.Rows.Count, "A").End(xlUp).Row
'Exit if the last row is 2 or smaller
If lngLastRow <= 2 Then
MsgBox "Nothing to compare!" & Chr(10) & "Aborting..."
Exit Sub
End If
'Compare Raw Data cell to Stock column and find a match
For lngRow = 2 To lngLastRow
'Only compare if there is something in column A to compare
If .Cells(lngRow, "A").Value2 <> vbNullString Then
'This is the actual MATCH / FIND
Set rngFound = .Range("C:C").Find(What:=.Cells(lngRow, "A").Value2, LookIn:=xlValues, LookAt:=xlWhole)
'Evaluate the result of the FIND = rngFound
If rngFound Is Nothing Then
.Cells(lngRow, 2).Value2 = "Not in Stock" 'not found
Else
.Cells(lngRow, 2).Value2 = "In stock in row " & rngFound.Row 'found
End If
End If
Next lngRow
End With
End Sub
如果您有问题,请告诉我。