我对vba很新,我为我在下面的代码中犯下的(很多)错误道歉。我在设置x
和y
变量时遇到错误,但在尝试运行索引和匹配组合时也是如此。任何帮助将不胜感激!
Public Sub indexandmatch()
Dim x As Range
Dim y As Range
Dim mycells As Range
Dim p As Variant
'workbooks(1) is the master workbook where I am trying to get the information from the other reports to be entered in to
Application.Workbooks(1).Activate
x = Application.Workbooks(2).Worksheets(1).Range("H:H")
y = Application.Workbooks(2).Worksheets(1).Range("I:I")
'range v is where I would like the values to be entered in the master
For Each mycells In Range("V:V")
p = Application.WorksheetFunction.Index(x, Application.WorksheetFunction.Match(mycells.Offset(0, -11).Value, y), 0)
mycells = p.Value
Next
End Sub
答案 0 :(得分:1)
您必须Set
任何对象变量,因为range
个
然后使用Application
对象函数将可能的错误包装为返回值,以便您可以使用IsError()
函数进行检查并相应地进行
最后避免使用Select
/ Activate
模式并使用完全限定范围引用
Public Sub indexandmatch()
Dim x As Range
Dim y As Range
Dim mycells As Range
Dim p As Variant
'workbooks(1) is the master workbook where I am trying to get the information from the other reports to be entered in to
Set x = Workbooks(2).Worksheets(1).Range("H:H")
Set y = Workbooks(2).Worksheets(1).Range("I:I")
'range v is where I would like the values to be entered in the master
For Each mycells In Workbooks(1).Worksheets("myMasterWorksheetName").Range("V:V") '<--| use fully qualified (up to worksheet and workbook) range reference. (change "myMasterWorksheetName" to you actual master workbook relevant worksheet name
p = Application.Match(mycells.Offset(0, -11).Value, y)
If Not IsError(p) Then
p = WorksheetFunction.Index(x, p, 0)
If Not IsError(p) Then mycells = p
End If
Next
End Sub