2017-08-11 148 views
2

我一直在尝试这个很长一段时间,虽然我得到了正确的答案,但我得到了Application-defined or Object defined error在vba中使用匹配公式返回一个行号

我有两张纸:Sheet2和Sheet3。这两张表都有一个“url”列。我想要的是获取Sheet2中URL的行号,并获取在Sheet3的列C(“匹配行”) 中打印的网址行位置。

这是我正在处理的数据的示例。 This is the Sheet3 which has url in the column B and Match Row in Column C This is the Sheet2 which has url in the column B

我得到的错误在这行

Matchvalue.Formula = "=Match(Worksheets("Sheet3").Cells(i, 2), Worksheets("Sheet2").Range("B:B"), 0) 

这是我已经试过:

Dim i As Integer 

i = 2 

Do While Worksheets("Sheet3").Cells(i, 2) <> "" 

    Worksheets("Sheet3").Cells(i, 14) = 
    WorksheetFunction.Match(Worksheets("Sheet3").Cells(i, 2), 
    Worksheets("Sheet2").Range("B:B"), 0) 
    i = i + 1 

Loop 
+0

您的代码不包括你说的是导致错误的行。 (Excel公式不能引用诸如'Worksheets(“Sheet3”)之类的对象。单元格(i,2)' - 它使用完全不同的语法,如'Sheet3!B5') – YowE3K

+0

除了写入列14而不是第3列,不是你的发布代码做你想要的吗? (它适用于我,一旦我摆脱了换行符,我认为它只是发布的问题的一部分,而不是实际的代码。) – YowE3K

回答

0

尝试下面的代码,代码的注释中解释:

Option Explicit 

Sub MatchUrl() 

Dim i As Long 
Dim MatchRng As Range 

With Worksheets("Sheet2") 
    ' set the match range is "Sheet2" 
    Set MatchRng = .Range("B1:B" & .Cells(.Rows.Count, "B").End(xlUp).Row) 
End With 

With Worksheets("Sheet3") 
    For i = 2 To .Cells(.Rows.Count, "B").End(xlUp).Row 
     ' check if successful match 
     If Not IsError(Application.Match(.Cells(i, 2), MatchRng, 0)) Then 
      .Cells(i, 2) = Application.Match(.Cells(i, 2), MatchRng, 0) 
     Else ' Match failed, raise some kind of error 
      .Cells(i, 2) = "Url not found in Sheet2!" 
     End If 
    Next i 
End With 

End Sub 
+0

Hi Shai Rado,完美地工作。非常感谢! d –

0

我不使用匹配,所以我不知道它的签名但: 通过转义行情也许...像

Matchvalue.Formula = "=Match(" & Worksheets("Sheet3").Cells(i, 2) & ";B:B;0)" 

为了避免引号,只需将它们加倍即可。

例如Debug.print "Hey ""You"" how are you ?"

+0

您需要使用'Sheet2!B:B'而不是'B: B'。 (而且我不确定,但是在分配给'.Formula'属性时,你不必使用英文公式语法吗?因此我认为'''因此需要'''s。但是,因为我使用Excel的英文版,所以我没有办法检查,所以很容易出错!) – YowE3K