2017-08-11 118 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