【问题标题】:Looping through files in order with Dir()使用 Dir() 按顺序循环文件
【发布时间】:2019-11-10 16:30:30
【问题描述】:

我正在尝试在 Excel 电子表格中插入几张图片,并将其另存为 PDF。我已经能够弄清楚如何对图片进行间隔并遍历文件夹中的所有图片,但我似乎无法弄清楚如何按顺序遍历图片。

我发现我可以使用 Dir 遍历特定文件夹中的 .jpg 文件,如以下问题所示:Loop through files in a folder using VBA? 和此问题 macro - open all files in a folder。它创造了奇迹,但我需要按顺序遍历图片。这些图片被标记为“PHOTOMICS0”,最终数字增加。

这是我正在使用的。

counter = 1
MyFile = Dir(MyFolder & "\*.jpg")
Do While MyFile <> vbNullString
    incr = 43 * counter
    Cells(incr, 1).Activate
    ws1.Pictures.Insert(MyFolder & "\" & MyFile).Select
    MyFile = Dir
    counter = counter + 1
Loop

到目前为止,MyFile 已从“PHOTOMICS0”变为“PHOTOMICS4”,依次为 9、10、7、2、3、8、6、5,最后为 1。重复时,它遵循相同的顺序。如何按数字顺序递增这些?

【问题讨论】:

  • 定义“按顺序”。您的意思是按升序或降序排序:文件大小、名称、创建日期、保存日期等...
  • 在这种情况下从“PHOTOMICS0”到“PHOTOMICS10”,或者任何最高的数字。所以我想上升。
  • 你最好的办法是加载数组中的所有文件名,然后在打开每个文件之前sort them
  • 这是个好主意。我不知道为什么我从来没想过。我会试一试,看看会发生什么。
  • stackoverflow.com/questions/4282940/…。 OP已将解决方案置于问题中。 ;)

标签: excel vba loops directory jpeg


【解决方案1】:

感谢cybernetic.nomadSiddharth Rout 的建议,我得以解决此问题。

我使用了这些帖子中的一些函数和代码行:

How to find numbers from a string?

How to sort an array of strings containing numbers

这是运行代码:

counter = 0
MyFile = Dir(MyFolder & "\*.jpg")
Do While MyFile <> vbNullString
    ReDim Preserve PMArray(counter)
    PMArray(counter) = MyFile
    MyFile = Dir
    counter = counter + 1
Loop

Call BubbleSort(PMArray)

b = counter - 1
For j = 0 To b
    a = j + 1
    If i > 24 Then a = j + 2
    incr = 43 * a
    Cells(incr, 1).Activate
    ws1.Pictures.Insert(MyFolder & "\" & PMArray(j)).Select
Next j

其中 BubbleSort 和 BubbleSort 中使用的相关函数是:

Sub BubbleSort(arr)
  Dim strTemp As String
  Dim i As Long
  Dim j As Long
  Dim lngMin As Long
  Dim lngMax As Long
  lngMin = LBound(arr)
  lngMax = UBound(arr)
  For i = lngMin To lngMax - 1
    For j = i + 1 To lngMax
      If onlyDigits(arr(i)) > onlyDigits(arr(j)) Then
        strTemp = arr(i)
        arr(i) = arr(j)
        arr(j) = strTemp
      End If
    Next j
  Next i
End Sub

Function onlyDigits(s) As Integer
    ' Variables needed (remember to use "option explicit").   '
    Dim retval As String    ' This is the return string.      '
    Dim retvalint As Integer
    Dim i As Integer        ' Counter for character position. '

    ' Initialise return string to empty                       '
    retval = ""

    ' For every character in input string, copy digits to     '
    '   return string.                                        '
    For i = 1 To Len(s)
        If Mid(s, i, 1) >= "0" And Mid(s, i, 1) <= "9" Then
            retval = retval + Mid(s, i, 1)
        End If
    Next

    ' Then return the return string.                          '
    retvalint = CInt(retval)
    onlyDigits = retvalint
End Function

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-09-23
    • 2018-01-07
    • 1970-01-01
    • 2023-03-23
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多