如何使用Excel VBA更改所选行的文件名

时间:2015-08-17 21:38:01

标签: excel vba excel-vba

我正在尝试编写一个VBA宏,它将文件名从B列中的文本更改为A列的文本。例如,如果我有:

A栏:堆栈溢出

B栏:问题

它会将Question.txt更改为Stack Overflow.txt。截至目前,我已将答案here中的代码略微修改为:

Sub rename()

Dim Source As Range
Dim OldFile As String
Dim NewFile As String

Set Source = Cells(1, 1).CurrentRegion

For Row = 2 To Source.Rows.Count
    OldFile = ActiveSheet.Range("D1").Value & ("\") & ActiveSheet.Cells(Row, 1) & (".pdf")
    NewFile = ActiveSheet.Range("D1").Value & ("\") & ActiveSheet.Cells(Row, 2) & (".pdf")

    ' rename files
    Name OldFile As NewFile

Next
End Sub

这很好用,但我试图让它只在选定的行上运行;我理想的最终结果是我可以选择我想要更改的15个非连续行,运行宏,并让它仅适用于那些15.我尝试了下面的代码但是ActiveSheet.Cells(Row,1)函数返回运行时错误1004,应用程序定义或对象定义错误;这有什么好办法吗?

Sub renameMain()

Dim OldFile As String
Dim NewFile As String
Dim rng As Range

Set rng = Selection

For Each Row In rng
    OldFile = ActiveSheet.Range("O1").Value & "\" & ActiveSheet.Range(Row, 2) & ".pdf"
    NewFile = ActiveSheet.Range("O1").Value & "\" & ActiveSheet.Range(Row, 1) & ".pdf"

    ' rename files
   Name OldFile As NewFile

Next Row
End Sub

非常感谢任何建议!

2 个答案:

答案 0 :(得分:0)

您似乎希望将Row用作int变量。事实并非如此。也许试试这个:

Sub renameMain()

Dim OldFile As String
Dim NewFile As String
Dim rng As Range
Dim i as long

Set rng = Selection

For i = 1 To rng.Rows.Count
    OldFile = ActiveSheet.Range("O1").Value & "\" & rng.Cells(i, 2) & ".pdf"
    NewFile = ActiveSheet.Range("O1").Value & "\" & rng.Cells(i, 1) & ".pdf"

    ' rename files
   Name OldFile As NewFile

Next i
End Sub

答案 1 :(得分:0)

可以使用.Areas集合访问Selection对象中的非连续行:

Option Explicit

Sub renameMain()
    Dim oldFile As String, newFile As String
    Dim selArea As Range, selRow As Range, staticVal As String

    With ActiveSheet
        staticVal = .Range("O1").Value2 & "\"
        For Each selArea In Selection.Areas
            For Each selRow In selArea.Rows
                oldFile = staticVal & .Cells(selRow.Row, 2).Value2
                newFile = staticVal & .Cells(selRow.Row, 1).Value2
                Name oldFile & ".pdf" As newFile & ".pdf"   'rename files
            Next
        Next
    End With
End Sub