簡體   English   中英

Excel VBA宏:在一個工作表中查找/匹配單元格到另一個工作表中的列

[英]Excel VBA Macros: Find/Match cells from one sheet to a column in another

好的,我有一本包含多張紙的工作簿。 工作表的名稱為:

輸入輸出硬件

輸入和輸出是與實際IP地址匹配的序列ID。
輸入1:192.168.0.1輸入2:192.168.0.2 ...

硬件有3列。 第一列具有設備,第二列具有輸入序列號和第三列輸出序列號。

烤面包機:輸入1:輸出3攪拌機:輸入2:輸出2 ...等

現在,通常情況下,我將使用Vlookup(A1,Inputs!A:B,2)和Vlookup(A1,Outputs!A:B,2),但是我必須將其合並到我們擁有的VBA宏中不知道如何。

Sub TrackHardware()

'~~~~~~~~~~~~~~~~~~~~~
'Activating Device
'~~~~~~~~~~~~~~~~~~~~~
currentOutputRow = 2
Dim test As String


For currentRow = 2 To 32768 'The last row of your data
'For Loop to go through contents of Hardware individually

    If Not (IsEmpty(Worksheets("Hardware").Range("A" & currentRow).Value)) Then
        'To Skip the empty cells 

            HWID=Worksheets("Hardware").Range("a" & currentvalue).Value
            'HWID is the search term coming from Sheet:'Hardware'

            Desc=Worksheets("Hardware").Range("D" & currentvalue).Value
            'Desc is the Plain Text description coming from Sheet:'Hardware'



            inputrow={Match pseudocode that didn't work(HWID, "Inputs", Range:= "A:B", 2) }
            outputrow={Match pseudocode that didn't work(HWID, "Outputs", Range:= "A:B", 2) }
            'trying to find the row # of search term in Sheets 'Input' and 'Output'

            Worksheets("Inputs").Range("C" & inputrow).Value = Desc
            Worksheets("Outputs").Range("C" & outputrow).Value = Desc
             'Pastes The Device Description to Input and Output Sheets



    End If
Next currentRow
'And on to the next line in 'Hardware'

End Sub

我也想考慮類似同一輸入/輸出或空白單元格上的2個設備的錯誤,但我想我可以自己找出這些錯誤。 該查找功能確實給我帶來了很多麻煩。

首先,如果您無法調用Application.Match函數,則似乎存在問題。 我不確定為什么會丟失它,但是我知道有些Office / Excel“有限”版本沒有完整的VBA功能。 我不確定安裝的情況是否如此。

現在,就您的問題...

要使用Application.Match函數:

Match功能采用單行或單列范圍輸入。 您試圖傳遞范圍"A:B" ,這將始終引發錯誤。 改為改為單個行/列范圍。

此外,第2個參數不是2的選項,它可以是-1(小於),0或False(精確)或1(大於)。 我不確定僅此一項會引發錯誤,但是無論如何您都應該修復它。

inputRow = Application.Match(HWID, Worksheets("Inputs").Range("A:A"), False)

如果找不到完全匹配的內容,則會引發錯誤,您可以這樣捕獲錯誤:

inputRow = Application.Match(HWID, Worksheets("Inputs").Range("A:A"), False)
If IsError(inputRow) Then
    'Do something like:
    MsgBox HWID & " not found!", vbInformation
    Exit Sub
End If

注意如果您實際上需要檢查列,則可以在Match函數上加倍使用,也可以使用range .Find方法。

Dim foundRange as Range
Set foundRange = Range("A:B").Find(HWID)
If Not foundRange Is Nothing Then
    inputRow = foundRange.Row
Else
    MsgBox HWID & " not found!", vbInformation
End If

使用WorksheetFunction.Match處理錯誤

捕獲Application.WorksheetFunction.Match錯誤應類似於:

inputRow = Empty
On Error Resume Next
inputRow = Application.WorksheetFunction.Match(HWID, Worksheets("Inputs").Range("A:A"), False)
If Err.Number <> 0 Then
    MsgBox "Match not found", vbInformation
    Exit Sub
End If
On Error GoTo 0

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM