简体   繁体   English

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

[英]How to fix syntax error when renaming the files in a specific folder in Excel VBA?

'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

I am using the above code for renaming the files in a folder, I am getting the syntax error in the line where I have marked ** before and after the particular line,我正在使用上面的代码重命名文件夹中的文件,在特定行前后标记 ** 的行中出现语法错误,

Name strFolder & strFileNameExisting As strFolder & strFileNameNew 

在此处输入图像描述

The code runs fine for me in Windows.代码在 Windows 中运行良好。 If you're using Mac, this might be the reason why it produces that error.如果您使用的是 Mac,这可能是它产生该错误的原因。

Your code should run fine, however, I suggest you add variable definitions at the beginning.您的代码应该可以正常运行,但是,我建议您在开头添加变量定义。 Here is the code with some modifications and the working excel sheet link这是经过一些修改的代码和工作表链接 excel

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 工作 Excel 文件

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM