首页 > 解决方案 > 我的宏无法执行 vlookup

问题描述

我有一个复杂的东西,它正在做很多复制粘贴到不同的文件,但是,我在下一行收到一个错误,错误是对象不支持这个属性或方法

.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?

标签: excelvba

解决方案


要分配公式,请使用范围对象的公式属性。此外,使用 Worksheet Name 属性来使用它,而不是公式中的工作表对象。

下面的代码应该适合您。

.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) & ")"

以下是 range 的关键属性之间的区别,以供将来参考:

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

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

. Value为您提供与 .Value2 相同的内容,除非单元格被格式化为货币或日期,它为您提供 VBA 货币(可能会截断小数位)或 VBA 日期。

资料来源:另一个 StackOverflow 答案


推荐阅读