簡體   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

我正在使用上面的代碼重命名文件夾中的文件,在特定行前后標記 ** 的行中出現語法錯誤,

Name strFolder & strFileNameExisting As strFolder & strFileNameNew 

在此處輸入圖像描述

代碼在 Windows 中運行良好。 如果您使用的是 Mac,這可能是它產生該錯誤的原因。

您的代碼應該可以正常運行,但是,我建議您在開頭添加變量定義。 這是經過一些修改的代碼和工作表鏈接 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

工作 Excel 文件

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM