应用程序定义或对象定义的错误1004和使用vlookup公式时的错误438



我正试图在一系列单元格上使用vlookup函数,该函数可以查找其他工作表中的值。然而,我遇到了一个运行时错误,上面写着"应用程序定义或对象定义的错误"

ActiveSheet.Range("$A$1", Selection.End(xlDown)).RemoveDuplicates Columns:=1, _
    Header:=xlYes
'In Summary Tab
Range("A1").CurrentRegion.Select
nRows = Selection.Rows.Count
' Places column headers in "Summary" tab
For iCounter = 2 To Sheets.Count
    Sheets(iCounter).Select
    Range("A1").CurrentRegion.Select
    nCols = Selection.Columns.Count
         For iColumn = 2 To nCols
            Sheets(iCounter).Select
                If (WorksheetFunction.IsNumber(Cells(2, iColumn)) = "TRUE") Then
                Cells(1, iColumn).Select
                Selection.Copy
                Sheets("Summary").Select
                ActiveCell.Offset(0, 1).PasteSpecial
                Application.CutCopyMode = False
                ActiveCell.Offset(1, 0).Select
                ActiveCell.Resize(nRows - 1, 1).Select
                Selection.Formula = "=vlookup(B2," & _
                    Range(sheets(icounter).selection).Address","& icolumn",false)"
                End If
        Next
Next

我还试着将vlookup公式编辑成这样,(其他一切都一样):

                Selection = Application.WorksheetFunction.VLookup( _
                    "B2", Sheets(iCounter).CurrentRegion.Select, iColumn, False)

但这给出了错误438"对象不支持此属性或方法"

甚至尝试编辑vlookup,但再次出现1004错误:

Selection=应用程序。工作表功能。VLookup("B2",表(iCounter)。范围(单元格(1,1),单元格(nColls,nRows)),iColumn,False)

它看起来就像您试图将公式插入到特定范围中。Application.WorksheetFunction.VLookup不插入公式,它用于向子/函数返回值,就像普通函数一样。因此,如果目标是插入一堆公式,那么最好的例子是正确的方法。

您在这行代码中看到错误的原因是您实际上没有引用范围。试试这个:

Selection.Formula = "=vlookup(B2," & Sheets(icounter).Name & "!" & _
                        Selection.Address & "," & icolumn & ",false)"

请注意,此代码调出工作表的名称,添加感叹号(!),然后添加所选内容的地址。

您可能也看到了错误,因为您的代码中缺少了几个与号(&)。

最后,请注意不要使用.Select.Selection.Activate。它们在VBA中有自己的位置,但会给您带来很多麻烦。有关如何避免使用.Select的更多信息,请查看Chris Neilsen的回答和Siddharth Rout的回答。

尝试添加:

On error resume next

在脚本的顶部。如果vlookup没有找到匹配项,它将返回一个错误。

如果返回错误,脚本将停止。

您当前的&最后的建议基本上是相同的,但语法不同——但我不认为这是你的问题的原因。请尝试下一个错误。

最新更新