[英]I try to use vlookup by using vba code but it doesn't work
我尝试通过下面的vba代码使用vlookup,但是它不起作用。 我想找到MMonth。 如何找到我的错误?
Sub abc()
Dim x As Workbook
Dim y As Workbook
Dim WB As Workbook
Dim PCFilePath As String
Dim PCFile As String
Dim RSFilePath As String
Dim RSFile As String
Dim Month As String
Dim MMonth As String
Dim Range As Range
Dim Date1 As Date
Dim Date2 As Date
PCFilePath = Worksheets("Sheet1").Range("B2")
PCFile = Worksheets("Sheet1").Range("B3")
RSFilePath = Worksheets("Sheet1").Range("B8")
RSFile = Worksheets("Sheet1").Range("B9")
Month = Worksheets("Sheet1").Range("B5")
Workbooks.Open (PCFilePath & PCFile), UpdateLinks:=0
Set x = Workbooks.Open(PCFilePath & PCFile)
Workbooks.Open (RSFilePath & RSFile), UpdateLinks:=0
Set y = Workbooks.Open(RSFilePath & RSFile)
Set WB = ThisWorkbook
'Vlookup the date
Set Range = y.Sheets("Sheet1").Range("B:E")
MMonth = Application.WorksheetFunction.VLookup(Month, Range, 4, True)
End Sub
问题:
Month
和Range
Range.Find
搜索 这里:
Sub abc()
Dim x As Workbook
Dim y As Workbook
Dim WB As Workbook
Dim PCFilePath As String
Dim PCFile As String
Dim RSFilePath As String
Dim RSFile As String
Dim mth As String
Dim MMonth As String
Dim Rng As Range
Dim Date1 As Date
Dim Date2 As Date
PCFilePath = Worksheets("Sheet1").Range("B2").Value
PCFile = Worksheets("Sheet1").Range("B3").Value
RSFilePath = Worksheets("Sheet1").Range("B8").Value
RSFile = Worksheets("Sheet1").Range("B9").Value
mth = Worksheets("Sheet1").Range("B5").Value
'Workbooks.Open (PCFilePath & PCFile), UpdateLinks:=0
Set x = Workbooks.Open(PCFilePath & PCFile)
'Workbooks.Open (RSFilePath & RSFile), UpdateLinks:=0
Set y = Workbooks.Open(RSFilePath & RSFile)
Set WB = ThisWorkbook
Dim fnd As Range
'Vlookup the date
Set Rng = y.Sheets("Sheet1").Range("B:E")
Set fnd = Rng.Find(mth)
If Not fnd Is Nothing Then
MMonth = fnd.Value
MsgBox "Value Found " & MMonth
End If
End Sub
一些修复:
Sub abc()
Dim x As Workbook, y As Workbook
Dim WB As Workbook
Dim PCFilePath As String
Dim RSFilePath As String
Dim sMonth As String
Dim MMonth As Variant '<< not string
Dim rngSearch As Range
With ActiveWorkbook.Worksheets("Sheet1")
PCFilePath = .Range("B2").Value & .Range("B3").Value
RSFilePath = .Range("B8").Value & .Range("B9").Value
sMonth = .Range("B5").Value
End With
Set x = Workbooks.Open(PCFilePath, UpdateLinks:=0)
Set y = Workbooks.Open(RSFilePath, UpdateLinks:=0)
Set WB = ThisWorkbook 'what's this for?
Set rngSearch = y.Sheets("Sheet1").Range("B:E")
'Drop the WorksheetFunction so it doesn't raise a
' run-time error of there's no match
MMonth = Application.VLookup(sMonth, rngSearch, 4, True)
If Not IsError(MMonth) then
Debug.Print "Got " & MMonth
Else
Debug.Print sMonth & " was not found!"
End If
End Sub
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.