简体   繁体   English

在变量VBA中将“”插入公式

[英]Insert “ ” into formula with variables VBA

I want to insert a vlookup into a range of cells that is defined by variables. 我想将vlookup插入由变量定义的一系列单元格中。 My problem is that the search criteria (I gave the variable the name x) in the vlookup needs to be in " ", else the vlookup doesnt work. 我的问题是,vlookup中的搜索条件(我给变量命名为x)必须位于“”中,否则vlookup不起作用。

But if I insert those " " into the formula in any way VBA thinks I'm trying to let it take x as a value. 但是,如果我以任何方式将那些“”插入公式中,VBA都会认为我试图让它以x为值。

Does anyone know how I can solve this problem? 有谁知道我该如何解决这个问题?

If there is anything else wrong with the code, please tell me too, I'm new to this. 如果代码还有其他问题,也请告诉我,我是新手。

Sub FindExchange()

n = Worksheets.Count
For k = n To 6 Step -1

    Dim ws As Worksheet
    Set ws = Worksheets(k)

Dim lColumn As Long
    lColumn = ws.Cells(1, Columns.Count).End(xlToLeft).Column


For i = lColumn To 1 Step -4

Dim lrow As Long
    lrow = ws.Cells(Rows.Count, i).End(xlUp).Row

x = Cells(1, i).Value

ws.Range(Cells(2, i + 2), Cells(lrow, i + 2)).FormulaLocal = "=vlookup(" & x & ";Sheet1!$B$2:$C$832;2;FALSE)"

Next i
Next k
End Sub

您可以尝试此解决方案,

"=vlookup(""" & x & """,Sheet1!$B$2:$C$832,2,FALSE)"
"=vlookup(" & """" & x & """" & ";Sheet1!$B$2:$C$832;2;FALSE)"

to get the double quotes " just add Chr(34) . 获得双引号"只需添加Chr(34)

change your FormulaLocal string to: 将您的FormulaLocal字符串更改为:

"=VLookup(" & chr(34) & x & chr(34) & ";Sheet1!$B$2:$C$832;2;FALSE)"

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM