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

我试图写一个VBAmacros,将列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 

这很好,但我试图让它只能运行在选定的行; 我的理想最终结果是,我可以select我想要更改的15个非连续行,运行macros,并只适用于那些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 

任何意见将不胜感激!

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

 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 

你似乎想要使用Row作为一个intvariables。 事实并非如此。 也许试试这个:

 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