Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/excel/28.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Vba 包含较长文件名的代码,其中文件名为数字_Vba_Excel_Directory_Create Directory - Fatal编程技术网

Vba 包含较长文件名的代码,其中文件名为数字

Vba 包含较长文件名的代码,其中文件名为数字,vba,excel,directory,create-directory,Vba,Excel,Directory,Create Directory,我正在尝试编辑其他人编写的代码。一般来说,我没有做VBA,也很少做编码 原始代码是为5位数字编写的,我们现在有6位数字的文件。我尝试复制代码,但将其更改为结尾处的下一个objFile上当前代码下方的6位数字。这是行不通的 这里的主要问题是我没有编写原始代码,也不理解逻辑。我试过把所有的5号改成6号,把99999改成999999。我已尝试从文件夹“”向下复制,将其更改为6位数字并粘贴到下面的下一个objFile。这也没用 Sub CopyPics() Dim objFSO As Object D

我正在尝试编辑其他人编写的代码。一般来说,我没有做VBA,也很少做编码

原始代码是为5位数字编写的,我们现在有6位数字的文件。我尝试复制代码,但将其更改为结尾处的下一个objFile上当前代码下方的6位数字。这是行不通的

这里的主要问题是我没有编写原始代码,也不理解逻辑。我试过把所有的5号改成6号,把99999改成999999。我已尝试从文件夹“”向下复制,将其更改为6位数字并粘贴到下面的
下一个objFile
。这也没用

Sub CopyPics()

Dim objFSO As Object
Dim objFolder As Object
Dim objFile As Object
Dim varDirectory As Variant
Dim objSubFolder As Object

Set objFSO = CreateObject("Scripting.FileSystemObject")
Set objFolder = objFSO.GetFolder(Application.ActiveWorkbook.Path)

Dim Dest As String
Dest = "R:\Field Assurance\FA PHOTOS AND INFORMATION\"

'Loop through each file in this folder
For Each objFile In objFolder.Files

    Folder = "" 'Empty old folder name
    MainFolder = "" 'Empty old folder name
    For i = 1 To Len(objFile.Name)
        Test = Mid(objFile.Name, i, 5)
        If Test >= 10000 And Test <= 99999 Then     'For files: Find any five numbers in a row and assume it to be the file number.
            Folder = "NC-" & Mid(objFile.Name, i, 5) 'If found, create new folder.
            i = Len(objFile.Name) 'In other words, take the first 5 numbers, then get out.
        End If
    Next

    For Each objSubFolder In objFolder.subfolders 'Find the main folder.
    If Right(Folder, 5) >= Mid(objSubFolder.Name, 4, 5) And Right(Folder, 5) <= Mid(objSubFolder.Name, 18, 5) Then 'If my file number is within the main folder bounds...
    MainFolder = objSubFolder.Name & "\" 'Use that folder.
    End If
    Next objSubFolder

    If Len(Folder) = 8 And Len(MainFolder) = 23 Then 'If real folders are identified...

    On Error Resume Next
    If Dir(Dest & MainFolder & Folder) = "" Then 'Check to see if the directory/folder does not exist...
        objFSO.CreateFolder (Dest & MainFolder & Folder) 'If not, make one.
    End If

    'Rename that file's directory to be the new one - aka cut and paste file into new folder.
    Name Application.ActiveWorkbook.Path & "\" & objFile.Name As Dest & MainFolder & Folder & "\" & objFile.Name

    End If

Next objFile

ActiveWorkbook.Close

End Sub
Sub-CopyPics()
作为对象的Dim objFSO
将文件夹变暗为对象
Dim objFile作为对象
Dim varDirectory作为变量
Dim objSubFolder作为对象
设置objFSO=CreateObject(“Scripting.FileSystemObject”)
设置objFolder=objFSO.GetFolder(Application.ActiveWorkbook.Path)
将Dest变暗为字符串
Dest=“R:\Field Assurance\FA照片和信息”
'循环浏览此文件夹中的每个文件
对于objFolder.Files中的每个objFile
Folder=“”清空旧文件夹名称
MainFolder=“”空旧文件夹名称
对于i=1到Len(objFile.Name)
Test=Mid(objFile.Name,i,5)

如果Test>=10000且Test=Mid(objSubFolder.Name,4,5)和Right(Folder,5)您还需要更改If条件下的下限。像

If Test >= 10000 And Test <= 99999 Then

如果Test>=10000,Test=100000,Test这比原始代码要复杂一些,但我认为它更健壮

轻度测试

Option Explicit

Sub CopyPics()

    'use constants for fixed values
    Const DEST As String = "R:\Field Assurance\FA PHOTOS AND INFORMATION\"

    Dim objFSO As Object, srcFolder As Object, objFile As Object
    Dim objSubFolder As Object, destFolder As Object, fNum, folderName, picFolderName
    Dim FileWasMoved As Boolean, sMsg

    Set objFSO = CreateObject("Scripting.FileSystemObject")

    Set srcFolder = objFSO.GetFolder(Application.ActiveWorkbook.Path) 'ThisWorkbook.Path ?
    Set destFolder = objFSO.GetFolder(DEST) 'parent destination folder

    'Loop through each file in this folder
    For Each objFile In srcFolder.Files

        FileWasMoved = False 'reset "moved" flag

        fNum = ExtractNumber(objFile.Name) 'get the file number

        If Len(fNum) > 0 Then 'any number found?

            folderName = "NC-" & fNum

            For Each objSubFolder In destFolder.subfolders 'Find the subfolder.
                If IsTheCorrectFolder(objSubFolder.Name, fNum) Then

                    picFolderName = objSubFolder.Path & "\" & folderName
                    If Not objFSO.folderexists(picFolderName) Then
                        objFSO.CreateFolder picFolderName
                    End If
                    'move the file
                    Name objFile.Path As picFolderName & "\" & objFile.Name
                    FileWasMoved = True 'flag file as moved
                    Exit For
                End If
            Next objSubFolder
        End If 'filename contains a number

        'if file was not moved then add it to the list....
        If Not FileWasMoved Then sMsg = sMsg & vbLf & objFile.Name

    Next objFile

    'warn user if some files were not moved
    If Len(sMsg) > 0 Then
        MsgBox "Some files were not moved:" & vbLf & sMsg, vbExclamation
    End If


End Sub

'Return true/false depending on whether this is the correct
'  folder to hold the specified filenumber 
Function IsTheCorrectFolder(folderName, fileNumber) As Boolean
    Dim arr, num1, num2, rv As Boolean
    rv = False 'default return value
    arr = Split(folderName, "thru") 'split folder name on "thru"
    If UBound(arr) = 1 Then 'should have two parts
        'get the numbers from each part and compare against the file number
        num1 = ExtractNumber(arr(0))
        num2 = ExtractNumber(arr(1))
        If Len(num1) > 0 And Len(num2) > 0 Then
            fileNumber = CLng(fileNumber) 'convenrt to Long for comparison
            rv = (fileNumber >= CLng(num1) And fileNumber <= CLng(num2))
        End If
    End If
    IsTheCorrectFolder = rv
End Function

'Extract the first 5- or 6-digit number from a string
' Match is "greedy" so if there are six digits it will match 6 and
'   not just the first 5...
Function ExtractNumber(txt)
    Dim re As Object, allMatches, rv
    Set re = CreateObject("VBScript.RegExp")
    re.Pattern = "(\d{5,6})"
    re.ignorecase = True
    re.Global = True
    Set allMatches = re.Execute(txt)
    If allMatches.Count > 0 Then rv = allMatches(0) 'if there's a match then return the first one
    ExtractNumber = rv
End Function
选项显式
子副本()
'将常量用于固定值
Const DEST As String=“R:\Field Assurance\FA照片和信息”
Dim objFSO作为对象,srcFolder作为对象,objFile作为对象
Dim objSubFolder作为对象,destFolder作为对象,fNum,folderName,picFolderName
Dim文件移动为布尔值,sMsg
设置objFSO=CreateObject(“Scripting.FileSystemObject”)
设置srcFolder=objFSO.GetFolder(Application.ActiveWorkbook.Path)'ThisWorkbook.Path?
设置destFolder=objFSO.GetFolder(DEST)'父目标文件夹
'循环浏览此文件夹中的每个文件
对于srcFolder.Files中的每个objFile
filewasmove=False“重置”已移动标志
fNum=ExtractNumber(objFile.Name)'获取文件号
如果Len(fNum)>0,则“找到任何数字?”?
folderName=“NC-”和fNum
对于destFolder.subfolders'中的每个objSubFolder,查找子文件夹。
如果是正确的文件夹(objSubFolder.Name,fNum),则
picFolderName=objSubFolder.Path&“\”&folderName
如果不是objFSO.folderexists(picFolderName),则
objFSO.CreateFolder picFolderName
如果结束
'移动文件
将objFile.Path命名为picFolderName&“\”&objFile.Name
filewasmove=True'将文件标记为已移动
退出
如果结束
下一个objSubFolder
如果“文件名”包含数字,则结束
'如果文件未移动,则将其添加到列表中。。。。
如果未移动文件,则sMsg=sMsg&vbLf&objFile.Name
下一个objFile
'如果某些文件未移动,则警告用户
如果Len(sMsg)>0,则
MsgBox“某些文件未移动:”&vbLf&sMsg,vb感叹号
如果结束
端接头
'根据这是否正确返回真/假
'文件夹以保存指定的文件号
函数将正确的文件夹(folderName、fileNumber)设置为布尔值
尺寸arr、num1、num2、rv为布尔值
rv=False“默认返回值
arr=Split(folderName,“thru”)'在“thru”上拆分文件夹名称
如果UBound(arr)=1,则“应具有两个部分
'获取每个零件的编号,并与文件编号进行比较
num1=提取编号(arr(0))
num2=提取次数(arr(1))
如果Len(num1)>0且Len(num2)>0,则
fileNumber=CLng(fileNumber)'更改为Long以进行比较

rv=(fileNumber>=CLng(num1)和fileNumber我认为您需要使用一个5位数的代码逐步完成,并跟踪值的变化。很可能还有其他依赖项,例如Len(Folder)=8和Len(MainFolder)=23。如果Folder=“NC-”&Mid(objFile.Name,I,5),那么对文件夹长度的测试可能会增加更改为6等…..本地窗口将很有用,可能会监视窗口。将一个文件放在它的工作位置,注意正在生成的值,以便更好地了解正在发生的事情。有很多关于调试的教程..如何使用F8逐步完成代码,如何使用立即窗口、监视窗口和locals窗口。这是一项非常宝贵的技能,需要花几个小时的时间来了解基本情况。您的所有文件现在都是6位数字,还是您仍在处理5位数字的名称?谢谢,我希望能够花时间学习所有这些。我的雇主不认为我在这个po上花时间学习编辑代码是有价值的int.我将不得不手动创建文件夹并移动文件,直到我在自己的私人时间内弄清楚为止。我很感激你的提示。我想学习这个。@TimWilliams我仍然处理5位数字的名字。我需要能够处理这两个。非常感谢你!!这非常有效!!我非常感谢你花时间帮助我。这我将为我节省数小时的文件夹创建和文件移动时间。到目前为止,我尝试使其工作失败。
Option Explicit

Sub CopyPics()

    'use constants for fixed values
    Const DEST As String = "R:\Field Assurance\FA PHOTOS AND INFORMATION\"

    Dim objFSO As Object, srcFolder As Object, objFile As Object
    Dim objSubFolder As Object, destFolder As Object, fNum, folderName, picFolderName
    Dim FileWasMoved As Boolean, sMsg

    Set objFSO = CreateObject("Scripting.FileSystemObject")

    Set srcFolder = objFSO.GetFolder(Application.ActiveWorkbook.Path) 'ThisWorkbook.Path ?
    Set destFolder = objFSO.GetFolder(DEST) 'parent destination folder

    'Loop through each file in this folder
    For Each objFile In srcFolder.Files

        FileWasMoved = False 'reset "moved" flag

        fNum = ExtractNumber(objFile.Name) 'get the file number

        If Len(fNum) > 0 Then 'any number found?

            folderName = "NC-" & fNum

            For Each objSubFolder In destFolder.subfolders 'Find the subfolder.
                If IsTheCorrectFolder(objSubFolder.Name, fNum) Then

                    picFolderName = objSubFolder.Path & "\" & folderName
                    If Not objFSO.folderexists(picFolderName) Then
                        objFSO.CreateFolder picFolderName
                    End If
                    'move the file
                    Name objFile.Path As picFolderName & "\" & objFile.Name
                    FileWasMoved = True 'flag file as moved
                    Exit For
                End If
            Next objSubFolder
        End If 'filename contains a number

        'if file was not moved then add it to the list....
        If Not FileWasMoved Then sMsg = sMsg & vbLf & objFile.Name

    Next objFile

    'warn user if some files were not moved
    If Len(sMsg) > 0 Then
        MsgBox "Some files were not moved:" & vbLf & sMsg, vbExclamation
    End If


End Sub

'Return true/false depending on whether this is the correct
'  folder to hold the specified filenumber 
Function IsTheCorrectFolder(folderName, fileNumber) As Boolean
    Dim arr, num1, num2, rv As Boolean
    rv = False 'default return value
    arr = Split(folderName, "thru") 'split folder name on "thru"
    If UBound(arr) = 1 Then 'should have two parts
        'get the numbers from each part and compare against the file number
        num1 = ExtractNumber(arr(0))
        num2 = ExtractNumber(arr(1))
        If Len(num1) > 0 And Len(num2) > 0 Then
            fileNumber = CLng(fileNumber) 'convenrt to Long for comparison
            rv = (fileNumber >= CLng(num1) And fileNumber <= CLng(num2))
        End If
    End If
    IsTheCorrectFolder = rv
End Function

'Extract the first 5- or 6-digit number from a string
' Match is "greedy" so if there are six digits it will match 6 and
'   not just the first 5...
Function ExtractNumber(txt)
    Dim re As Object, allMatches, rv
    Set re = CreateObject("VBScript.RegExp")
    re.Pattern = "(\d{5,6})"
    re.ignorecase = True
    re.Global = True
    Set allMatches = re.Execute(txt)
    If allMatches.Count > 0 Then rv = allMatches(0) 'if there's a match then return the first one
    ExtractNumber = rv
End Function