Vba在文件夹中打开第四个excel文件

时间:2018-01-16 23:17:53

标签: excel-vba vba excel

我需要一个VBA代码才能打开文件夹中的第四个Excel文件而不管文件的名称,在文件上执行操作并关闭它

我尝试过使用

Sub OpenDoStuff()

Dim fs As FileSearch
Dim i As Integer
Dim wbk As Workbook

Set fs = Application.FileSearch

With fs
.LookIn = "C:\Users\Saulo\Desktop\MINING"
.Filename = "*.xls"
For i = 3 To .Execute()
    Set wbk = Workbooks.Open(.FoundFiles(i))
    'do stuff here
wbk.Close(SaveChanges:=True)
End With
End Sub

欢迎任何建议。

2 个答案:

答案 0 :(得分:0)

Application.Filesearch已从Office 2007中的Excel中删除。您使用的是哪个版本的Office?

假设你确实有Application.Filesearch可用:

Sub OpenDoStuff()

    Dim fs As FileSearch
    Dim i As Integer
    Dim wbk As Workbook

    Set fs = Application.FileSearch

    With fs
    .LookIn = "C:\Users\Saulo\Desktop\MINING"
    .Filename = "*.xls"
    .Execute()

    If .FoundFiles.Count >= 4 Then
        Set wbk = Workbooks.Open(.FoundFiles(3))
       'do stuff here
        wbk.Close(SaveChanges:=True)
    End If
End With
End Sub

答案 1 :(得分:0)

需要对文件进行排序。

我正在使用WMI来获取文件。 WMI适用于大多数环境。

DisplayFourthFile依赖辅助函数对数组进行排序。您可以使用文件的开头轻松替换MsgBox。

WMI不支持ORDER BY,因此也就是排序功能。

Sub DisplayFourthFile()

    ' Get the Data, Unfortunately WMI Has No ORDER BY
    Set objWMIService = GetObject("winmgmts:\\.\root\cimv2")
    Set colFiles = objWMIService.ExecQuery _
        ("Select Name from CIM_DataFile  where Drive='C:' and Path = '\\Users\\Saulo\\Desktop\\MINING\\' And Name Like '%XLS%'")

    ' Set to Array
    Dim files() As String
    ReDim files(1 To colFiles.count)
    Dim name As String
    Dim i As Integer: i = 1
    For Each objFile In colFiles
      files(i) = objFile.name
      i = i + 1
    Next

    ' Sort the Data
    QuickSort files, 1, colFiles.count

    If colFiles.count >= 4 Then

         Set wbk = Workbooks.Open(files(i))
         ' do stuff here
         wbk.Close(SaveChanges:=True)

    End If

    Set objWMIService = Nothing
    Set colFiles = Nothing
End Sub

Public Sub QuickSort(vArray As Variant, inLow As Long, inHi As Long)

  Dim pivot   As Variant
  Dim tmpSwap As Variant
  Dim tmpLow  As Long
  Dim tmpHi   As Long

  tmpLow = inLow
  tmpHi = inHi

  pivot = vArray((inLow + inHi) \ 2)

  While (tmpLow <= tmpHi)

     While (vArray(tmpLow) < pivot And tmpLow < inHi)
        tmpLow = tmpLow + 1
     Wend

     While (pivot < vArray(tmpHi) And tmpHi > inLow)
        tmpHi = tmpHi - 1
     Wend

     If (tmpLow <= tmpHi) Then
        tmpSwap = vArray(tmpLow)
        vArray(tmpLow) = vArray(tmpHi)
        vArray(tmpHi) = tmpSwap
        tmpLow = tmpLow + 1
        tmpHi = tmpHi - 1
     End If

  Wend

  If (inLow < tmpHi) Then QuickSort vArray, inLow, tmpHi
  If (tmpLow < inHi) Then QuickSort vArray, tmpLow, inHi

End Sub