简体   繁体   English

Excel VBA中的子或函数未定义错误

[英]sub or function not defined error in excel vba

I am trying to run a code that I found also here. 我正在尝试运行在这里也找到的代码。 the code is removing duplicates on each column on each spreed sheet on a workbook treating it as a separate entity. 代码将删除工作簿上每张纸上每列的重复项,将其视为一个单独的实体。 whenever I try to run the code the compiler error says "sub or function not defined" and there is a yellow highlight on the most upper part and the "LastCell" got a blue highlight. 每当我尝试运行代码时,编译器错误都会显示“未定义子函数或函数”,并且最上部显示黄色,而“ LastCell”显示为蓝色。 I already add the solver reference but still it gives me the same error. 我已经添加了求解器参考,但仍然给我同样的错误。 I just can't figure out what the problem is if it's on the code or should I add another reference. 我只是不知道问题出在什么地方,如果在代码上还是应该添加另一个引用。

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

Looks like lasy cell is the function you thought you had. 看起来懒散的单元格就是您认为的功能。 We is the worksheet passed in. Thee function will use something like 我们是传入的工作表。您的函数将使用类似

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

End function

After deciphering your code snippet, this is the best that I can come up with. 解密您的代码段后,这是我能想到的最好的方法。

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

Copy that code to a module code sheet in your VBA project. 将该代码复制到VBA项目中的模块代码表中。 It can tested with a short sub procedure like the following. 可以使用以下简短的子过程进行测试。

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的解决方案,请确保将函数LastCell也复制到您的代码中。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM