我有一个excel工作表的文件夹,还有一个工作表,其中一个列的条目对应于文件夹中工作表的文件名。
工作表名称右侧的列有一个数字,我想将其粘贴到每个相应的工作表中...但它不起作用...这是我目前的代码:
Sub FraisRank()
Dim folderPath As String
Dim filename As String
Dim filenameshort As String
Dim wb As Workbook
Dim fraislist As Workbook
Dim find As Range
Dim sel As Range
folderPath = "C:\Users\richard\Desktop\temp"
If Right(folderPath, 1) <> "\" Then folderPath = folderPath + "\"
Set fraislist = Workbooks.Open("C:\Users\richard\desktop\frais list.xlsx")
filename = Dir(folderPath & "*.*")
Do While filename <> ""
Application.ScreenUpdating = False
Set wb = Workbooks.Open(folderPath & filename)
filenameshort = Left(filename, Len(filename) - 4)
Set sel = fraislist.Sheets(1).Range("A1:A164")
Set find = sel.find(What:=filenameshort, After:=ActiveCell, LookIn:=xlFormulas, _
LookAt:=xlWhole, SearchOrder:=xlByRows, SearchDirection:=xlNext, _
MatchCase:=False, SearchFormat:=False)
If find Is Nothing Then
MsgBox ("Cell " & filenameshort & " not found")
Else
find.Offset(, 1).Resize(1, 1).Copy
ActiveSheet.Range("$H$5").PasteSpecial Paste:=xlPasteValues
End If
ActiveWorkbook.Save
ActiveWorkbook.Close
filename = Dir
Loop
End Sub
目前我收到运行时错误'13',在'Set find = ...'部分输入不匹配。一般来说,我真的不明白如何在'fraislist'工作簿中的选定单元格上运行'.find'......
答案 0 :(得分:1)
ActiveCell
的问题在于它始终会引用Activesheet
,因此应避免使用Activecell/Select/Activate/ActiveSheet/Activeworkbook
之类的语句。始终创建相关对象并使用它们
在您的情况下,ActiveSheet
不一定是fraislist.Sheets(1)
,因此ActiveCell
可能不会引用正确的工作表,因此,最好完全限定它。
如果您将After:=ActiveCell
更改为After:=fraislist.Sheets(1).Range("A1")
,那么您的代码将引用正确的表单,它将起作用。