【问题标题】:how to write an excel formula in vba?如何在vba中编写一个excel公式?
【发布时间】:2013-04-23 03:59:20
【问题描述】:

我是 vba 新手。我有一个excel公式,我想把它写成vba代码。但我有一个问题。我不知道该怎么做。有谁能够帮我? 这是公式:

IFERROR(LOOKUP(2^15,SEARCH(G$6:G$8,B6),G$6:G$8),"")

实际上,我在 sheet2 的 G 列中有一些关键字,我想在 sheet1 的 B 列中搜索它们,其中包含文本。如果有任何匹配项,我希望 vba 代码在第一张表的列(例如 D)中返回匹配的关键字,如果没有,则将相应的单元格留空。

我不知道该怎么做。有人可以帮帮我吗?

【问题讨论】:

  • 此函数是否在工作表中进行评估?我认为您不能在 Search 函数中使用 Range 参数。
  • 此外,您包含的公式与您认为该公式所做的描述并不真正匹配。即,您在公式中没有引用 Sheet1 或 Sheet2...

标签: excel vba


【解决方案1】:

即使您提供的描述似乎与您提供的功能不匹配,我也会对此进行尝试。

我首先使用IsError 函数和Application.Match 来检查是否在Sheet1 的Range("B:B") 中找到lookup_value

Dim lookup_value as String ' the value you're searching for.'
Dim found_value as String ' the value to return if a match is found.'

lookup_value = "edit this value!"  '<~~ This is the value you're searching for. Edit as needed.'

If Not IsError(Application.Match(lookup_value, Sheets("Sheet1").Range("B:B"),False) Then
    'If the above does not yield an error, then set the found_value based on VLOOKUP.'
    found_value = Application.WorksheetFunction.VLookup(lookup_value, Sheets("Sheet1").Range("B:D"),2,False)
Else:
    'If the MATCH function returns an error, set the found_value = vbNullString.
    found_value = vbNullString
End If

从此结果中,您可以简单地将单元格值设置为函数的结果found_value

ActiveCell.Value = found_valueRange("A1").Value = found_value

【讨论】:

  • VLoopup? :D 我还注意到你开始使用像 &lt;~~ 这样的 cmets ;)
  • 啊!错字!我非常喜欢&lt;~~ :)
  • [offtopic]啊哈..只是我已经使用了 8 年了...这就是我在网上识别我的代码的方式:P[offtopic]
  • + 1 我也认为用户想要这个。顺便说一句,您是否知道实际上可以使用简单的countif 而不是 IsError(Application.Match(lookup_value, Sheets("Sheet1").Range("B:B"),False) 来检查另一列中是否存在值?类似If Not Application.CountIf(Sheets("Sheet1").Range("B:B"), lookup_value) = 0 Then
  • 是的,您也可以使用CountIf。不过我使用Application.Match 函数,因为该方法也可以用于数组变量。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多