简体   繁体   中英

How to get file path from different sheet in VBA

I am new in VBA. I have two sheets ie sheet1 has path of input Directory and Output directory. On sheet2 i am started to code. i wants to read data from multiple xls files that are are stores in a folder . this folder path is specified in sheet1. i wants to copy all files headers from all xls files to sheet3 in a column. my code is working well but i have given file path directly but i wants to get it from other sheet. Please help me. Below is my code and i have attched sheet1. Sheet1数据

Public Sub CommandButton1_Click()
'DECLARE AND SET VARIABLES
Dim wbk As Workbook
Dim Filename As String
Dim Path As String
Dim mainwb As Workbook
Dim ws As Worksheet
 Dim search_result As Range   'range search result
    Dim blank_cell As Long
Dim wb As Workbook
Path = "D:\Testing\Data\Input\"
Filename = Dir(Path & "*.xls")
'--------------------------------------------
'OPEN EXCEL FILES
 Do While Len(Filename) > 0  'IF NEXT FILE EXISTS THEN
    Set wbk = Workbooks.Open(Path & Filename)
    'MySheet = Application.Caller.Worksheet.Name
    'Set sh = MySheet()
   'Variable = ActiveSheet.Name
  ' Sheets(Variable).Range("A1:D1").Copy
    'Sheets("Sheet2").Column(B2).Select.Activate.Paste
   ' Sheets("Sheet2").Active
    'Columns("B2").Select
  Set wbk = ActiveWorkbook
  Variable = ActiveSheet.Name
  wbk.Sheets(Variable).Rows(1).EntireRow.Copy

 Workbooks("Tool.xlsm").Activate
' Workbooks("DFT Tool.xlsm").Sheets("Sheet2").Activate
'ActiveWorkbook.ActiveSheet

  'Sheets("Sheet2").Activate
    'ActiveSheet.Columns("E").Select
  ' Range("E1").End(xlDown).Offset(1, 0).Select
    'ActiveSheet.Paste

 Set wb = ActiveWorkbook
  Set ws = wb.Sheets("Sheet2")
    For Each cell In ws.Columns(3).Cells
        If IsEmpty(cell) = True Then cell.Select: Exit For
    Next cell
 Selection.PasteSpecial Paste:=xlPasteValues, Transpose:=True

' Selection.PasteSpecial Paste:=xlPasteValues, Transpose:=True
    wbk.Close savechanges:=False
    Filename = Dir
Loop
End Sub

Thanks in Advance

Try

Path = Cells(2,2).value

This takes the Value of Cell B2 and stores it in the Path variable. Another possibility:

Filename = Dir(Cells(2,2).value & "*.xls")

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