如何修复在Excel VBA中重命名特定文件夹中的文件时的语法错误?

xzlaal3s  于 2022-12-05  发布在  其他
关注(0)|答案(2)|浏览(210)
'This method renames all the filenames in a folder
Sub RenameAllFilenamesInAFolder()
    Dim intRowCount As Integer
    Dim intCtr As Integer
    Dim strFileNameExisting As String
    Dim strFileNameNew As String
    Dim strFolder As String
     
    'Set the folder path
    strFolder = "C:\Users\rchandramohan\"
     
    With Sheet1
        'Find the total rows count in the sheet
        'This will be the last non-blank cell in column A...
        intRowCount = .Cells(.Rows.Count, "A").End(xlUp).Row
         
        'Loop through from the 2nd row (1st row is Heading)
        'till the total rows in the sheet
        For intCtr = 2 To intRowCount
            'Get the existing filename from the cell
            strFileNameExisting = .Range("A" & intCtr)
    
            'Get the new filename from the cell
            strFileNameNew = .Range("B" & intCtr)
             
            'Rename the file
          ** Name strFolder & strFileNameExisting As strFolder & strFileNameNew **
        Next intCtr
    End With
     
    'Display an appropriate message, once complete
    MsgBox "All files renamed successfully!", _
                        vbInformation, "All files renamed"
End Sub

我正在使用上面的代码重命名文件夹中的文件,我在特定行的前后标记了**的地方得到了语法错误,

Name strFolder & strFileNameExisting As strFolder & strFileNameNew

0pizxfdo

0pizxfdo1#

如果你使用的是Mac,这可能就是它产生错误的原因。

2hh7jdfx

2hh7jdfx2#

您的代码应该运行良好,但是,我建议您在开始时添加变量定义。

Sub RenameAllFilenamesInAFolder()
Dim intRowCount As Integer
Dim intCtr As Integer
Dim strFileNameExisting As String
Dim strFileNameNew As String
Dim strFolder As String

strFolder = Application.ActiveWorkbook.Path & "\"
With Sheet1
    intRowCount = .Cells(.Rows.Count, "A").End(xlUp).Row
    For intCtr = 2 To intRowCount
        If Not .Range("C" & intCtr) Then
            strFileNameExisting = .Range("A" & intCtr)
            strFileNameNew = .Range("B" & intCtr)
            Name strFolder & strFileNameExisting As strFolder & strFileNameNew
            .Range("C" & intCtr) = True
        End If
    Next intCtr
End With
MsgBox "All files renamed successfully!", _
       vbInformation, "All files renamed" 
End Sub

Working Excel File

相关问题