简体   繁体   English

Excel VBA 中的 Vlookup 公式

[英]Vlookup Formula in Excel VBA

I have an Excel sheet with locked cells.我有一张带有锁定单元格的 Excel 表。 Some cells are unlocked to input values.一些单元格被解锁以输入值。 There are many values to input therefore I'm trying to write a Macro that will: select the unlocked cells in the Active Sheet and fill the selected cells with a Vlookup formula that looks up the input values based on the first column and relevant rows in the same sheet from a table on a separate sheet.有很多值要输入,因此我正在尝试编写一个宏,它将: select 活动工作表中未锁定的单元格并使用 Vlookup 公式填充选定的单元格,该公式根据第一列和相关行查找输入值同一工作表来自单独工作表上的表。 I have tried the below:我尝试了以下方法:

Sub SelectUnlockedCells()
'Update 20130830
Dim WorkRng As Range
Dim OutRng As Range
Dim Rng As Range
On Error Resume Next
Set WorkRng = Application.ActiveSheet.UsedRange
Application.ScreenUpdating = False
For Each Rng In WorkRng
    If Rng.Locked = False Then
        If OutRng.Count = 0 Then
            Set OutRng = Rng
        Else
            Set OutRng = Union(OutRng, Rng)
        End If
    End If
Next
If OutRng.Count > 0 Then OutRng = Application.WorksheetFunction.VLookup("A" & ActiveRow.Value, Worksheets(2).Columns("A:C").Select, Worksheets(2).Columns(3).Select, False)
Application.ScreenUpdating = True
End Sub

I know my problem occurs in the last 4 lines in the Vlookup Worksheet Function, because if I say:我知道我的问题出现在 Vlookup Worksheet Function 的最后 4 行,因为如果我说:

If OutRng.Count > 0 Then OutRng = 1 + 1

The unlocked input cells are imputed correctly as 2. Therefore I suspect my Vlookup object selection is not correct.未锁定的输入单元被正确估算为 2。因此我怀疑我的 Vlookup object 选择不正确。

Any help would be great, thanks!任何帮助都会很棒,谢谢!

You're not putting a formula in those cells at all, you're trying to put a value in there, and the syntax you have is completely wrong for that anyway.您根本没有在这些单元格中放置公式,而是试图在其中放置一个值,无论如何,您所拥有的语法是完全错误的。 Try:尝试:

If OutRng.Count > 0 Then OutRng.FormulaR1C1 = "=VLookup(RC1,'" & worksheets(2).name & "'!C1:C3,3,FALSE)"

Simple solution I found was as I suspected - object referencing inside the vlookup was wrong.我发现的简单解决方案正如我所怀疑的那样 - 在 vlookup 中引用 object 是错误的。 Also, the Application Worksheet Function was redundant in this case.此外,在这种情况下,应用程序工作表 Function 是多余的。 In the third last line solution was:在倒数第三行的解决方案是:

If OutRng.Count > 0 Then OutRng = "=VLOOKUP(A11,'Sheet1'!Table1,3,FALSE)"

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

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