使用一个工作表中的值,检查另一个工作表上的值并返回到单元格

时间:2017-01-27 14:52:22

标签: excel vba excel-vba range

我有两本工作簿。我们称之为" Main"和" Aux"。

我正在编写一个将在" Main"并将使用来自" Aux"。

的数据

"主"在一个工作表上有一个人员列表。对于每个人,我想查看工作簿" Aux"这个人拥有等级> = 3的技能,将它们连接起来并填写工作簿上的单元格" Main"。

这是我迄今为止所写的代码。问题是范围指的是" Main"工作簿,我想要的数据是" Aux"工作簿。

当专栏" A"有"技术"

  • G栏" Aux" book保留了每个人的名字。
  • D栏" Aux"拥有技能的名称
  • 变量deb和deb2用于使用MsgBox进行调试

代码:

Public Function Arroz(name As String) As String

    Dim rngFound As Range
    Dim strFirst As String
    Dim strID As String
    Dim strDay As String
    Dim skillsAs String
    Dim deb As String
    Dim deb2 As String


    strID = "Person number one"
    strDay = "Technical"
    skills= ""


    Set rngFound = Workbooks("Aux.xlsx").Sheets("Skills Mao").Columns("G").Find(strID, Cells(Rows.Count, "G"), xlValues, xlWhole)

    If Not rngFound Is Nothing Then
        strFirst = rngFound.Address
        Do
            deb = Cells(rngFound.Row, "A").Text
            deb2 = Cells(rngFound.Row, "M").Value
            MsgBox deb
            MsgBox deb2
            If LCase(Cells(rngFound.Row, "A").Text) = LCase(strDay) And Cells(rngFound.Row, "M").Value >= 4 Then
               skills = skills & Cells(rngFound.Row, "D").Text & " ,"
            End If
            Set rngFound = Columns("G").Find(strID, rngFound, xlValues, xlWhole)
        Loop While rngFound.Address <> strFirst
    End If
    strLast = rngFound.Address
    Set rngFound = Nothing

    Arroz = competencies
    Exit Function
    End Function

有人可以帮我弄清楚我做错了吗?

1 个答案:

答案 0 :(得分:1)

您的问题是在未指定工作表的情况下使用Cells。执行此操作时Cells将引用活动工作表,即命名为“Main”。尝试这样的事情:

' ------ More of your existing code above ------
strID = "Person number one"
strDay = "Technical"
skills= ""

' ----- My added snippit -----
Dim shAux as Worksheet
Set shAux = Workbooks("Aux.xlsx").Sheets("Skills Mao")
Set rngFound = shAux.Columns("G").Find(strID, shAux.Cells(Rows.Count, "G"), xlValues, xlWhole)

然后使用shAux.Cells,只要您希望该工作表中的单元格代替Cells