![](/img/trans.png)
[英]Looping INDEX-MATCH VBA with Sub or Function not defined error
[英]VBA Worksheet Function Index-Match throwing up type mismatch error
我正在研究一個使用 VBA 來完成索引匹配 function 的宏。 vba 出錯,說我的類型不匹配,但是我在腳本前面以類似的方式使用相同的變量並且運行沒有問題。 查找值位於另一個名為“項目”的工作表中。 代碼片段如下。 任何幫助,將不勝感激。
Sub Test_1
Dim ws As Worksheet, ws1 As Worksheet, ws2 As Worksheet, ws3 As Worksheet, ws4 As Worksheet
Dim wb As Workbook
Dim i As Long, j As Long
Dim r As Range, cell As Range, aCell As Range, LastRow As Range
Dim strSearch As String
Set wb = ThisWorkbook
With wb
strSearch = "Column_1"
i = 0
Set LastRow = ws4.Cells(Rows.Count, 1).End(xlUp)
Set aCell = ws4.Rows(1).Find(What:=strSearch, LookIn:=xlValues, LookAt:=xlWhole, SearchOrder:=xlByRows, SearchDirection:=xlNext, MatchCase:=False, SearchFormat:=False)
If Not aCell Is Nothing Then
For i = LastRow To 2 Step -1
ws4.Cells(i, aCell).Value = WorksheetFunction.Index(wb.Sheets("Items").Range("D:D"), WorksheetFunction.Match(ws4.Cells(i, aCell), wb.Sheets("Items").Range("A:A")))
On Error Resume Next
Next i
Else: 'Do Nothing
End If
End With
End Sub
Sub Test_1()
Dim ws As Workbook: Set wb = ThisWorkbook
Dim dws As Worksheet: Set dws = wb.Worksheets("Sheet4") ' ???
Dim sws As Worksheet: Set sws = wb.Worksheets("Items")
Dim Header As String: Header = "Column_1"
Dim hCell As Range: Set hCell = dws.Rows(1).Find(Header, _
dws.Rows(1).Cells(dws.Rows(1).Cells.Count), xlFormulas, xlWhole)
If Not hCell Is Nothing Then
Dim hCol As Long: hCol = hCell.Column
Dim LastRow As Long
Set LastRow = dws.Cells(dws.Rows.Count, "A").End(xlUp).Row
Dim lrg As Range: Set lrg = sws.Range("A:A") ' Lookup Range
Dim srg As Range: Set srg = sws.Range("D:D") ' Source Range
Dim cIndex As Long
Dim i As Long
For i = 2 To LastRow
' dws.Cells(i, col) ??? - You usually don't overwrite the value...
cIndex = Application.Match(dws.Cells(i, col).Value, lrg, 0)
If IsNumeric(cIndex) Then
' ... that you were searching for ???
dws.Cells(i, col).Value = srg.Cells(cIndex).Value
End If
Next i
End If
End Sub
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.