繁体   English   中英

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

[英]How to Change the File Names of Selected Rows using Excel VBA

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

列A:堆栈溢出

B栏:问题

它将Question.txt更改为Stack Overflow.txt。 截至目前,我已经对此处的答案中的代码进行了一些修改,以使其变为:

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

任何建议将不胜感激!

您似乎想将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

可以使用其.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

暂无
暂无

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

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