【问题标题】:Is there a way in VBA to find a String in a Directory and then Loop?VBA中有没有办法在目录中找到一个字符串然后循环?
【发布时间】:2019-11-05 06:41:42
【问题描述】:

我在下面部分解决了我的问题。在一天中,我想将我的文件增加 1。

目前,如果 Excel 在 mypath 中检测到同名文件,我可以将同名(相同字符串)的文件加 1

例如,如果 VBA 在目录中检测到Red 06-22-2019 #8,我的文件将另存为Red 06-22-2019 #9

但是,我希望我的所有文件都增加 1(不管文件名是否相同),只检测一个共享子字符串(当前日期)。

也就是说,不是 Excel 检测相同的文件名并将 mycount 增加 1(如下面的代码所示),我希望 Excel 在同一目录中检测是否有任何文件名与今天的日期 (mydate)存在。如果是这样,该文件名将递增 1。(各种文件名仅共享相同的当前日期,因此理论上我可以在一天中每天递增许多不同的文件名)

因此,当我将具有与 Red 文件名相似的子字符串(当前日期)的不同文件名 (Blue 06-22-2019) 保存时,Excel 会将 Blue 文件名增加 1(因为它例如,在我要保存“Blue”文件的同一目录中检测到 8 个“Red”文件)

Blue 文件将另存为 Blue 06-22-2019 #9(对于本示例)

我曾多次尝试在循环中工作,使用了许多排列,但我是整个编码领域的新手

而且我找不到任何关于在网络上检测子字符串的信息

如果可以的话请帮忙:)

Sub helpMePlease()   
      Dim myfile As String
      Dim mypath As String 
      Dim mycount As Integer 
      Dim mydate As String            

      mydate = Format(Now(), "MM-DD-YYYY") 
      mypath = "C:\Users\Robert\Colors\

      'do some code here, like opening a workbook and translating data, etc.

      'now, to save the opened workbook I came up with the below code    
      'it says increase my file name by 1 unless file name does not exist within my path

    Do
          mycount = mycount + 1
          myfile = mypath & "Blue " & mydate & " #" & mycount & ".xlsx"     
    Loop Until Dir(myfile) = ""          

    ActiveWorkbook.SaveAs Filename:=myfile

End Sub

【问题讨论】:

    标签: vba string loops directory


    【解决方案1】:

    您应该能够在 dir 中使用通配符,例如 Dir(mypath & "*" & mydate & " #" & mycount & ".xlsx")。在这种情况下,它将查看具有相同日期的所有文件。

    【讨论】:

    • 感谢 Alex 它有效,我们“通配符” mydate 并从 Dir 函数中删除 myfile,因为它包含可以从一个文件名更改为另一个文件名的字符串。欣赏它男人
    • 循环直到 Dir(mypath & "*" & mydate & " #" & mycount & ".xlsx") = ""
    • 编辑,通配符 * 用作变体,因此任何子字符串或子字符串集将在文件之间更改,只需在 Dir 函数中将子字符串替换为 * 跨度>
    猜你喜欢
    • 2013-06-18
    • 2020-12-17
    • 1970-01-01
    • 2021-08-24
    • 1970-01-01
    • 2014-08-21
    • 2011-02-16
    • 1970-01-01
    • 2017-04-10
    相关资源
    最近更新 更多