我的宏无法执行vlookup

时间:2018-12-17 04:14:07

标签: excel vba excel-vba

我有一个复杂的组件,正在将很多副本粘贴到不同的文件中,但是,我在下一行遇到错误,错误是对象不支持此属性或方法

.Range("Q" & i).Value="if(P" & i & "=" & Chr(34) & "Y" & Chr(34) & ",vlookup(A" & i & "," & OutShVar & "!$A:$BP,68,0)," & Chr(34) & "Not Available" & Chr(34) & ")"

(我正在复制与问题相关的粘贴部分)

  Set OutShVar=ThisWorkbook.Worksheets("MasterReport")
  Set RngConcat=OutShVar.Range("A:A")

  Set wMain=Workbooks.open(ForePath & sfn)
  Call OpenLink 'Performs tasks on another report after opening it


  'After doing a bunch of things on the OpenLink report,
    'i want to do a vlookup on that report that will take things from the excel
    'workbook where the macro is i.e., OutShVar and RngCon'

   'On Master list/Refresh
   if .Range("P" & i).Value = "N" Then
   .Range("Q" & i).Value="Not inscope"
  Else
   If not IsError(Application.Match(.Range("A" & i).Value,RngConcat,0) Then
    .Range("Q" & i).Value="if(P" & i & "=" & Chr(34) & "Y" & Chr(34) & ",vlookup(A" & i & "," & OutShVar & "!$A:$BP,68,0)," & Chr(34) & "Not Available" & Chr(34) & ")"
    'This is where the problem is, not sure if this is right way to do the vlookup?

1 个答案:

答案 0 :(得分:1)

要分配公式,请使用Range对象的Formula属性。另外,使用工作表名称属性来使用它,而不是在公式中使用工作表对象。

下面的代码适合您。

.Range("Q" & i).Formula = "= IF(P" & i & "=" & Chr(34) & "Y" & Chr(34) & ",VLOOKUP(A" & i & ",'" & OutShVar.Name & "'!$A:$BP,68,0)," & Chr(34) & "Not Available" & Chr(34) & ")"

以下是范围的关键属性之间的差异,以供将来参考:

Text给出一个字符串,表示该单元格在屏幕上显示的内容。使用.Text通常不是一个好主意,因为您可以得到####

Value2为您提供单元格的基础值(可以为空,字符串,错误,数字(双精度)或布尔值)

Value与.Value2相同,除了单元格的格式设置为货币或日期外,它还为您提供了VBA货币(可能会截断小数位)或VBA日期。

来源:Another StackOverflow answer