从目录中已关闭的工作簿中获取单元格值-如何循环浏览所有现有文件?

时间:2019-05-26 23:01:33

标签: excel vba

当我指定目录时,我有一个工作代码来检索封闭工作簿中的特定单元格。我试图使这段代码遍历所述目录中的所有现有工作簿,并从每个文件中检索相同的单元格。

这是我到目前为止在循环中使用的代码(我也包括使用的函数):

Private Function GetValueFromClosedWorkbook(path, file, sheet, ref)    
    Dim arg As String, xFolder As String

    If Right(path, 1) <> "\" Then path = path & "\"

    If Dir(path & file) = "" Then
        GetValueFromClosedWorkbook = "File not found."
        Exit Function
    End If

    arg = "'" & path & "[" & file & "]" & sheet & "'!" & _
    Range(ref).Address(, , xlR1C1)         'create the argument
    GetValueFromClosedWorkbook = ExecuteExcel4Macro(arg)
End Function


Sub TestGetValueFromClosedWorkbook()        
    Dim p As String, xFolder As String        
    Dim s As String, a As String, f(1 To 2) As String, z As Long

    xFolder = "\\generic path"

    For z = 1 To 2
        s = "Sheet1"
        a = "A1"
        p = xFolder '& "\*.xlsx"
        f(z) = Dir(p & "\*.xlsx")  

        Do While f(z) <> ""
            ActiveSheet.Range("A" & (z + 7)) = GetValueFromClosedWorkbook(p, f(z), s, a)   
            f(z) = Dir()
        Loop
    Next z
End Sub

这将获得正确的单元格,然后粘贴到单元格A8中的活动工作表中。

唯一的问题是,当它遍历第二个文件时,它仍然从第一个文件中获取单元格。为什么会这样呢?或者,如何确保第二个循环从第二个工作簿中检索单元格?

1 个答案:

答案 0 :(得分:1)

循环有点混乱,您正在覆盖这些值。请查看下面的更正代码:

Sub TestGetValueFromClosedWorkbook()

    Dim p As String, xFolder As String

    Dim s As String, a As String, f As String, z As Long

    xFolder = "\\generic path"

    s = "Sheet1"
    a = "A1"
    p = xFolder '& "\*.xlsx"

    f = Dir(p & "\*.xlsx")
    Do While f <> ""

        ActiveSheet.Range("A" & (z + 7)) = GetValueFromClosedWorkbook(p, f, s, a)

        f = Dir()
        z = z + 1
    Loop
End Sub