简体   繁体   English

Excel 中的 VBA - 更改列中的 VLOOKUP 公式以根据静态单元格值插入工作表名称

[英]VBA in Excel - Changing a VLOOKUP formula in a column to insert name of sheet based on static cell value

I have a workbook with multiple sheets, and new sheets will be added regularly, titled by [mmm yy] format.我有一个包含多张工作表的工作簿,将定期添加新工作表,标题为 [mmm yy] 格式。 In my main sheet ("ContactList"), I have an IF formula with a 'nested' VLOOKUP formula in three columns to pull the respective numbers from the appropriate sheet, and I have a cell that has the date in the format I want.在我的主工作表(“ContactList”)中,我有一个 IF 公式,在三列中有一个“嵌套”VLOOKUP 公式,用于从相应的工作表中提取相应的数字,并且我有一个单元格,其中包含我想要的格式的日期。 I want my script to look at the cell with the date in it, and use that cell's value to update the columns of VLOOKUP formulas to match that.我希望我的脚本查看包含日期的单元格,并使用该单元格的值更新 VLOOKUP 公式的列以匹配它。 For example, in February, the cell on my main sheet will say "Feb 20", so my VLOOKUP formulas will look in the sheet titled "Feb 20".例如,在 2 月,我的主工作表上的单元格将显示“Feb 20”,因此我的 VLOOKUP 公式将在标题为“Feb 20”的工作表中查找。 In March, that cell will update, and I want my script (preferably automatically but tied to a button is alright) to update all the VLOOKUP functions to now be looking in the "Mar 20" sheet. 3 月,该单元格将更新,我希望我的脚本(最好是自动但绑定到按钮的)更新所有 VLOOKUP 函数,以便现在查看“3 月 20 日”表。

I feel like I've been trying a million things and keep getting various errors, but I'm just stuck now.我觉得我已经尝试了 100 万次并不断出现各种错误,但我现在卡住了。 My latest attempt was to set the parts of the formula as variables, then set other variables to be those parts parsed together.我最近的尝试是将公式的部分设置为变量,然后将其他变量设置为一起解析的部分。

        Sub Update_Counts()
        Dim rng As Range
        Dim cellnum As Integer
        Dim curr As Object
        Dim v1 As String, v2 As String, v3 As String, v4 As String, v5a As String, v5b As String, v5c As String
        Dim v6a As String, v6b As String, v6c As String, strFormC As String, strFormMR As String, strFormMD As String

        v1 = "=IF(VLOOKUP("
        v2 = Cells(cell.Row, "A")
        v3 = ",'"
        v4 = Cells(1, 6).Value
        v5a = "'!B7:F50, 2, FALSE) = 0, 'EMPTY', VLOOKUP("
        v5b = "'!B7:F50, 3, FALSE) = 0, 'EMPTY', VLOOKUP("
        v5c = "'!B7:F50, 4, FALSE) = 0, 'EMPTY', VLOOKUP("
        v6a = "'!B7:F50, 2, FALSE))"
        v6b = "'!B7:F50, 3, FALSE))"
        v6c = "'!B7:F50, 4, FALSE))"

        strFormC = v1 & v2 & v3 & v4 & v5a & v2 & v3 & v4 & v6a
        strFormMR = v1 & v2 & v3 & v4 & v5b & v2 & v3 & v4 & v6b
        strFormMD = v1 & v2 & v3 & v4 & v5c & v2 & v3 & v4 & v6c

        Set curr = Worksheets("ContactList").Cells(cellnum, 6)
        Set rng = Sheets("ContactList").Range("F3:H55")

            For cellnum = 3 To 55
                If Cells(2, 6).Value = "Commercial Total" Then
                 curr.Value = strFormC
                ElseIf Cells(2, 7).Value = "Medicare" Then
                 curr.Value = strFormMR
                ElseIf Cells(2, 8).Value = "Medicaid" Then
                 curr.Value = strFormMD
                End If
            Next cellnum
    End Sub

That's what I have thus far.这就是我迄今为止所拥有的。 I'm currently getting "Run-time error '424'; Object Required".我目前收到“运行时错误‘424’;需要对象”。 I had thought having curr as an object would allow me to get through it, but I think my cellnum value is the "needs to be an object" portion of the For statement.我曾认为将curr作为对象可以让我通过它,但我认为我的cellnum值是For语句的“需要成为对象”部分。 However, I'm not sure how to get the cell values in there without how it's set up.但是,我不确定如何在没有设置的情况下获取单元格值。 I had tried a "For Each" loop but got a myriad of issues there as well.我曾尝试过“For Each”循环,但也遇到了无数问题。 I wasn't able to find any examples of people wanting to update their cells' formulas by including a cell value, but perhaps I just wasn't looking in the right spot.我找不到任何想要通过包含单元格值来更新其单元格公式的示例,但也许我只是没有找到正确的位置。 Any advice is much appreciated!非常感谢任何建议!

As I put in my comment, you don't need to use VBA to achieve this.正如我在评论中所说,您不需要使用 VBA 来实现这一点。

If I'm reading your code correctly , I think you just need the following formula in cell A3 and copy it down:如果我正确阅读您的代码,我认为您只需要在单元格 A3 中使用以下公式并将其复制下来:

=IF(VLOOKUP($A3,INDIRECT("'"&$F$1&"'!B7:F50"),IF($F$2="Commercial Total",2,IF($G$2="Medicare",3,IF($H$2="Medicaid",4,1))),FALSE)=0,"EMPTY",VLOOKUP($A3,INDIRECT("'"&$F$1&"'!B7:F50"),IF($F$2="Commercial Total",2,IF($G$2="Medicare",3,IF($H$2="Medicaid",4,1))),FALSE))

This is on the assumptions I've made from reading your code that:这是基于我通过阅读您的代码所做的假设:

Cell F1 contains the name of the sheet you want to get the data from.单元格 F1 包含要从中获取数据的工作表的名称。

One of Cells F2, G2 and H2 will contain the keywords Commercial Total, Medicare and Medicaid respectively.单元格 F2、G2 和 H2 之一将分别包含关键字 Commercial Total、Medicare 和 Medicaid。


If you want some code though, this is how I'd build the LOOKUP flexibly:如果你想要一些代码,这就是我灵活构建 LOOKUP 的方式:

Sub Update_Counts()

    Dim rng As Range

    With Sheets("ContactList")

        Set rng = .Range("F3:F55")

        lookupformula = "=IF(VLOOKUP(A<rownum>,'<sheetname>'!B7:F50,<colnum>,FALSE)=0,""EMPTY"",VLOOKUP(A<rownum>,'<sheetname>'!B7:F50,<colnum>,FALSE))"

        For Each c In rng.Cells

            sheetname = .Cells(1, 6).Value
            thisrow = c.Row

            If .Cells(2, 6).Value = "Commercial Total" Then
                colnum = 2
            ElseIf .Cells(2, 7).Value = "Medicare" Then
                colnum = 3
            ElseIf .Cells(2, 8).Value = "Medicaid" Then
                colnum = 4
            End If

            finalformula = Replace(Replace(Replace(lookupformula, "<rownum>", thisrow), "<sheetname>", sheetname), "<colnum>", colnum)

            c.Formula = finalformula

        Next

    End With

End Sub

I figured it out from @CLR 's answer, thank you!我从@CLR 的回答中弄清楚了,谢谢! I was struggling because I figured out the date value to stop the script from trying to import a new document, but the If/ElseIf criteria were getting a little muddied.我很挣扎,因为我找到了阻止脚本尝试导入新文档的日期值,但是 If/ElseIf 标准变得有点混乱。 Since the headers all always existed, it was inputting the last condition across the board, meaning I was getting column 3 data for all three columns.由于标题始终存在,因此它正在全面输入最后一个条件,这意味着我正在获取所有三列的第 3 列数据。 I am sure there's a neater way to do it, but at least for me, I'm happy with splitting the three functions and having a button run all three.我确信有一种更简洁的方法可以做到这一点,但至少对我来说,我很高兴将三个功能分开并让一个按钮同时运行所有三个功能。

Private Sub CommandButton1_Click()
Update_Counts_COM
Update_Counts_MR
Update_Counts_MD
End Sub

Sub Update_Counts_COM()

    Dim rng As Range

    With Sheets("ContactList")

        Set rng = .Range("F3:F21,F24:F27,F30:F51")

        lookupformula = "=IFERROR(IF(VLOOKUP(A<rownum>,'<sheetname>'!B7:F59,<colnum>,FALSE)=0,""EMPTY"",VLOOKUP(A<rownum>,'<sheetname>'!B7:F59,<colnum>,FALSE)), ""Not Found"")"

        For Each c In rng.Cells

            sheetname = .Cells(1, 6).Value
            thisrow = c.Row

            If .Cells(2, 6).Value = "Commercial Total" Then
                colnum = 2

            End If

                finalformula = Replace(Replace(Replace(lookupformula, "<rownum>", thisrow), "<sheetname>", sheetname), "<colnum>", colnum)
                c.Formula = finalformula
        Next
    End With

End Sub

Sub Update_Counts_MR()

    Dim rng As Range

    With Sheets("ContactList")

        Set rng = .Range("G3:G21,G24:G27,G30:G51")

        lookupformula = "=IFERROR(IF(VLOOKUP(A<rownum>,'<sheetname>'!B7:F59,<colnum>,FALSE)=0,""EMPTY"",VLOOKUP(A<rownum>,'<sheetname>'!B7:F59,<colnum>,FALSE)), ""Not Found"")"

        For Each c In rng.Cells

            sheetname = .Cells(1, 6).Value
            thisrow = c.Row

            If .Cells(2, 7).Value = "Medicare" Then
                colnum = 3

            End If

                finalformula = Replace(Replace(Replace(lookupformula, "<rownum>", thisrow), "<sheetname>", sheetname), "<colnum>", colnum)
                c.Formula = finalformula
        Next
    End With

End Sub

Sub Update_Counts_MD()

    Dim rng As Range

    With Sheets("ContactList")

        Set rng = .Range("H3:H21,H24:H27,H30:H51")

        lookupformula = "=IFERROR(IF(VLOOKUP(A<rownum>,'<sheetname>'!B7:F59,<colnum>,FALSE)=0,""EMPTY"",VLOOKUP(A<rownum>,'<sheetname>'!B7:F59,<colnum>,FALSE)), ""Not Found"")"

        For Each c In rng.Cells

            sheetname = .Cells(1, 6).Value
            thisrow = c.Row

            If .Cells(2, 8).Value = "Medicaid" Then
                colnum = 4

            End If

                finalformula = Replace(Replace(Replace(lookupformula, "<rownum>", thisrow), "<sheetname>", sheetname), "<colnum>", colnum)
                c.Formula = finalformula
        Next
    End With

End Sub

was what ended up working for me!是什么最终为我工作! Thanks everyone :)谢谢大家 :)

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

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