当我运行我的代码时,即使所有变量都被定义为变体,我仍然会遇到类型不匹配错误。我不确定问题是什么。我是VBA的新手,所以我很感激任何帮助!谢谢!
Sub drink_2()
Columns("E:H").Insert shift:=xlToRight, copyorigin:=xlFormatFromLeftOrAbove
Range("F6").value = "Drink Price"
Range("G6").value = "Drink Revenue"
Range("H6").value = "Gross Sales less Drink Revenue"
Dim i As Variant
Dim item As Variant
Dim drink_price As Variant
Dim wbk As Workbook
Set wbk = Workbooks.Open("C:\Users\username\Documents\vlookup table drink prices.xlsx")
Dim lookup_range As Variant
lookup_range = wbk.Worksheets("Sheet1").Range("A:B").value
i = 7
Do While Cells(i, 1).value <> ""
item = Cells(i, 1).value
Cells(11, 1).value = item
drink_price = Application.WorksheetFunction.VLookup(item, lookup_range, 2, False)
zero_check = Application.WorksheetFunction.IfError(drink_price, 0)
If IsError(Application.WorksheetFunction.VLookup(item, lookup_range, 2, False)) Then
Cells(i, 6).value = ""
Else
Cells(i, 6).value = Application.WorksheetFunction.VLookup(item, lookup_range, 2, False)
End If
Cells(i, 7).Formula = Cells(i, 6).value * Cells(i, 5).value
Cells(i, 8).Formula = Cells(i, 4).value - Cells(i, 7).value
Range("F:G").NumberFormat = "#,##0.00"
i = i + 1
Loop
Cells.EntireColumn.AutoFit
End Sub
答案 0 :(得分:0)
这可能就是问题所在:
lookup_range = wbk.Worksheets("Sheet1").Range("A:B").value
您应该获取范围,而不是值,因此您需要使用set关键字并删除value属性。
set lookup_range = wbk.Worksheets("Sheet1").Range("A:B")