xlLastCell只能工作一半的时间

时间:2014-08-04 11:04:36

标签: excel ms-access excel-vba access-vba vba

我试图通过以下代码删除excel中的重复项:

Set rng = Range("A1", Range("A1").SpecialCells(xlLastCell))
    rng.removeduplicates Columns:=8, Header:=xlYes

这种方法似乎有一半的时间。有时它有效,有时会给我以下错误:

enter image description here

搜索运行时错误1004给我的信息是不应该有字符串,超过911个字符,但实际情况并非如此。在同一个excel文件上多次运行代码时,它在50%的时间内都能正常运行。

我在ms access 2007中运行代码,但我的所有引用都已打开。问题是当然,如​​何解决这个问题,但任何其他更好的方法来轻松删除我的重复项也将受到赞赏。谢谢。

编辑:完整代码:

Const xlLastCell As Long = 11
Const xlYes As Long = 1

Public Function formatreports(FileName As String) As String
Dim xl As Excel.Application
Dim xlwb As Excel.Workbook
Dim xlsh As Excel.Worksheet
Dim rng As Range
Dim newname As String

Set xl = CreateObject("Excel.Application")
xl.DisplayAlerts = False
xl.Visible = False

Set xlwb = xl.Workbooks.Open(FileName)
Set xlsh = xlwb.Worksheets(1)

    'its MFR0004; This is solely for import reasons
    xlsh.Rows("1:4").Delete
    xlsh.Rows("2").Delete
    xlsh.Columns("A:B").Delete
    xlsh.Columns("B").Delete
    'This as well
    xlsh.Range("J1") = "Total Weight"
    xlsh.Range("L1") = "Net Weight"
    xlsh.Range("O1") = "Gross Weight"
    xlsh.Range("AA1") = "Delivery Date"

    Set rng = xlsh.Range("A1", Range("A1").SpecialCells(xlLastCell))
    rng.removeduplicates Columns:=8, Header:=xlYes

    newname = Left(FileName, Len(FileName) - 4) & ".XLSX"
    xlwb.SaveAs newname, FileFormat:=51
    formatreports = newname

xlwb.Save
xlwb.Close
xl.Quit
Set xl = Nothing
End Function

1 个答案:

答案 0 :(得分:2)

问题是你的细胞不是完全合格的。

你需要尝试这样的事情

' change sheet1 to the relevant worksheet
With ThisWorkbook.Sheets("Sheet1")
    Set rng = .Range("A1", .Range("A1").SpecialCells(xlLastCell))
    rng.RemoveDuplicates Columns:=8, Header:=xlYes
End With

On旁注:因为您说您正在使用Access,并且此代码有时会起作用,这意味着您可能正在使用Early Binding。如果您不是,那么您必须将这些添加到代码顶部

Const xlLastCell As Long = 11
Const xlYes As Long = 1