简体   繁体   中英

How to Add Specific Cell in Excel document using VBA

This is my scenario, I have a path that contains all excel files. Now, I want to implement a solution that will insert the current "Filename" in specific cell for that file.

For Example:

sample.xls
Sample2.xls
Sample3.xls

Inside that sample.xls, I want to inset the filename "sample" without the extension on cell "E7" and "E8" then save this file.

I currently have this formula to get the filename without the extension:

=MID(CELL("filename",A1),SEARCH("[",CELL("filename",A1))+1,SEARCH(".",CELL("filename",A1))-1-SEARCH("[",CELL("filename",A1)))

Here are a few codes that might help you on the way:

For the last row in a workbook:

LastRow = ActiveWorkbook.ActiveSheet.Cells(ActiveWorkbook.ActiveSheet.Rows.Count, "a").End(xlUp).Row

ActiveWorkbook can be replaced by "Workbooks(NameofWorkbook)".

ActiveWorksheet can be replaced by "Sheets(NameofSheet)".

For adding the paths of the excel files to column a:

Sub LoopThroughFiles()
    Dim MyObj As Object, MySource As Object, file As Variant
    file = Dir("c:\testfolder\")

    While (file <> "")
       ActiveWorkbook.ActiveWorksheet.Cells((LastRow+1), 1).Value = file
    Wend
    file = Dir
End Sub

Not too sure this works, you'll have to test it.

****EDIT_1****

For the file extensions the following might be useful (found on another question):

FileExtStr = "." & LCase(Right(wb.Name, Len(wb.Name) - InStrRev(wb.Name, ".", , 1)))

wb.name can later be replaced by the cells holding the path (by WB.WS.Cells(x, y).Value)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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