【问题标题】:Looping through multiple excel files, Finding a string, and returning the values in adjacent cells循环遍历多个excel文件,查找字符串,并返回相邻单元格中的值
【发布时间】:2019-04-05 15:10:56
【问题描述】:

我有 400 个 excel 文件(技术报告),每个文件都有 5 个不同名称的选项卡。我需要创建一个主电子表格,其中包含每个报告的某些信息(信息始终在同一个选项卡上)

我有一个代码(从此处复制),可用于在特定单元格中查找信息。

问题是报告的结构不一致,好消息是在我搜索的信息的相邻单元格上,总是有相同的文本“水位:”。

我正在寻找一个可以搜索此文本字符串、复制相邻单元格并将其返回到此主电子表格的宏。

请看我提到的代码:

  Sub Test()
' Adjust the path below as required
MyPath = "C:\Users\bcf00637\Desktop\pilelogs\V2\"    ' Set the path.
myname = Dir(MyPath, vbNormal)    ' Retrieve the first entry.
Do While myname <> ""    ' Start the loop.
    ' Ignore the current directory and the encompassing directory.
    If myname <> "." And myname <> ".." Then
        If (GetAttr(MyPath & myname) And vbNormal) = vbNormal Then
           ActiveCell.FormulaR1C1 = "='" & MyPath & "[" & myname & "]Approval Form'!R1C1" ' change the part after the ] to your sheets name
           ' also change the R1C1 on the end to pick up the cell you want ie R2C3 for cell C2
           ' do NOT change the 1st one (.FormulaR1C1) this is part of the command.
           ActiveCell.Offset(0, 1).Value = myname
           ActiveCell.Offset(1, 0).Select
        End If
    End If
    myname = Dir
Loop

End Sub

【问题讨论】:

    标签: excel vba


    【解决方案1】:

    试试这个。由于您的问题的详细信息不清楚,因此在 cmets 中进行了一些查询。

    Sub Test()
    
    Dim r As Range, wb As Workbook
    
    mypath = "C:\Users\bcf00637\Desktop\pilelogs\V2\"
    myname = Dir(mypath, vbNormal)
    
    Do While myname <> ""
        If myname <> "." And myname <> ".." Then
            Set wb = Workbooks.Open(Filename:=mypath & myname)
            If (GetAttr(mypath & myname) And vbNormal) = vbNormal Then
                'have left this line as not sure what it does
                ActiveCell.FormulaR1C1 = "='" & mypath & "[" & myname & "]Approval Form'!R1C1"
                'change sheet name to suit
                Set r = wb.Sheets("Sheet1").usedrange.Find(what:="Water level:", lookat:=xlWhole,matchcase:=false)
                If Not r Is Nothing Then
                    'puts cell to the right in column A of master sheet
                    ThisWorkbook.Sheets(1).Range("A" & Rows.Count).End.xlUp(2).Value = r.Offset(1).Value
                End If
            End If
            wb.Close False
        End If
        myname = Dir
    Loop
    
    End Sub
    

    【讨论】:

    • 哇,好快,感谢您的回答,它并没有真正起作用,但是谢谢!
    • 哈,你想告诉我它是怎么不工作的,我可以让它工作吗?
    • 好吧,我复制了代码,删除了“activecell.formulaR1C1...”这一行,改变了路径和工作表;运行宏,然后..什么也没发生。
    • 您需要检查我的 cmets 并单步执行代码以查看发生了什么。可能找不到文本,或者它复制了错误的单元格。
    • SJR,代码现在在这一行显示错误: Set r = wb.Sheets("Casing Record").Find(what:="Water level:", lookat:=xlWhole, MatchCase:=False) "对象不承认方法"??我可能有点超出我的深度......
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-03-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-01-03
    • 1970-01-01
    相关资源
    最近更新 更多