excel vba中sub或者函数没有定义的错误

我正在尝试运行我在这里也find的代码。 该代码是删除工作簿上的每个spreed工作表上每个列上的重复处理它作为一个单独的实体。 每当我尝试运行代码时,编译器错误都会提示“sub or function not defined”,最上面的部分有一个黄色突出显示,“LastCell”显示了一个蓝色突出显示。 我已经添加了求解器参考,但它仍然给我同样的错误。 我只是不知道是什么问题,如果是在代码上,或者我应该添加另一个引用。

Sub Removeduplicates() Dim ws As Workbook Dim lLastcol As Long Dim lLastrow As Long Dim i As Long For Each ws In ThisWorkbook.Worksheets lLastcol = LastCell(ws).Column For i = 1 To lLastcol lLastrow = LastCell(ws, i).Row With ws .Range(.Cells(1, i), .Cells(lLastrow, i)).Removeduplicates Columns:=1, Header:=xlNo End With Next i Next ws End Sub 

看起来像lasy cell是你认为的function。 我们是传入的工作表。你的function将使用类似的东西

 Function lastcell(w as worksheet) as range Set Lastcell=w.range("a" & w.rows.count).end(xlup) End function 

破译你的代码片段之后,这是我能想到的最好的。

 Function lastCell(ws As Worksheet, _ Optional c As Variant, _ Optional r As Variant) As Range With ws If IsMissing(c) And IsMissing(r) Then Set lastCell = .Cells.SpecialCells(xlCellTypeLastCell) ElseIf IsMissing(c) And Not IsMissing(r) Then Set lastCell = .Cells(r, .Columns.Count).End(xlToLeft) ElseIf IsMissing(r) And Not IsMissing(c) Then Set lastCell = .Cells(.Rows.Count, c).End(xlUp) Else Set lastCell = .Cells(r, c) End If End With End Function 

将该代码复制到VBA项目中的模块代码表。 它可以用一个简短的子程序进行testing,如下所示。

 Sub test() Dim ws1 As Worksheet Set ws1 = ActiveSheet Debug.Print lastCell(ws1).Address(0, 0) '<~~ last cell on worksheet Debug.Print lastCell(ws1, 3).Address(0, 0) '<~~ last used cell in column C Debug.Print lastCell(ws1, , 4).Address(0, 0) '<~~ last used column on row 4 End Sub 

如果你在这里指的是Darren Bartrup-Cook的解决scheme,请确保将函数LastCell复制到你的代码中。