[英]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.