首页 > 解决方案 > 是否有条件因素来检查带有字母的文件名然后执行代码?

问题描述

我正在编写将执行以下操作的代码: 1. 根据同一根文件夹中的 excel 文件的文件名创建文件夹 2. 将 excel 文件移动到新创建的同名文件夹

我在设置将检查文件夹中的 excel 文件的代码时遇到问题,因为它包含我想跳过的其他 excel 文件。文件名之间的区别在于,我要排除的是文件名开头带有日期的文件名。

这是我到目前为止所拥有的


Sub Create_Folder()

Dim ParentFolder As String

ParentFolder = ThisWorkbook.Path

myFile = Dir(ParentFolder)

Do While myFile <> "Australia Formatting" 'Or "20*"
    Debug.Print myFile
    Debug.Print Left(myFile, InStr(1, myFile, "_") - 1)
    MkDir (ParentFolder & Left(myFile, InStr(1, myFile, "_") - 1))
    Name ParentFolder & myFile As ParentFolder & Left(myFile, InStr(1, myFile, "_") - 1) & "\" & myFile
    myFile = Dir
Loop
End Sub

标签: excelvba

解决方案


Sub Create_Folder()

Dim ParentFolder As String
dim s as string

ParentFolder = ThisWorkbook.Path & "\"

myFile = Dir(ParentFolder & "*.xl??") 'only want to look at excel files

Do While myFile <> "" 'keep looking until all files have been checked
    if myfile ="Australia Formatting" Or isdate(left(myfile,8)) then
          'skip
    else
       s=Left(myFile, InStr(1, myFile, "_") - 1)
       MkDir (ParentFolder & s)
       Name ParentFolder & myFile As ParentFolder & s & "\" & myFile
   end if
    myFile = Dir()
Loop
End Sub

'在我的手机上完成,所以我无法测试 - 可能是拼写错误


推荐阅读