Копировать ячейку из рабочих книг
Проверьте константы, и вы готовы к работе.Она выдаст ошибку, если рабочая книга не получила указанный рабочий лист («financial_report»).
Код
'*******************************************************************************
' Purpose: Copies a cell value from all workbooks in a folder to a column
' in this workbook.
'*******************************************************************************
Sub CopyCellFromWorkbooks()
' Source Folder Path
Const cStrPath As String = _
"C:\"
' Source Worksheet Name/Index
Const cStrSource As Variant = "financial_report"
Const cVntSource As Variant = 7 ' Source Column Letter/Number
' Target Worksheet Name/Index
Const cStrTarget As Variant = "Sheet1"
Const cVntTarget As Variant = 1 ' Target Column Letter/Number
' FSO Objects
Dim objFSO As Object, objFolder As Object, objFile As Object
Dim objTarget As Worksheet ' Target Worksheet (ThisWorkbook)
Dim lngTarget As Long ' Target Column
Dim lngSource As Long ' Source Column
Set objFSO = CreateObject("Scripting.FileSystemObject")
Set objFolder = objFSO.GetFolder(cStrPath)
Set objTarget = ThisWorkbook.Sheets(cStrTarget)
For Each objFile In objFolder.Files
If objFSO.GetExtensionName(objFile.Name) = "xls" Then
With Workbooks.Open(objFile.Path).Worksheets(cStrSource)
With objTarget
lngTarget = _
.Cells(.Rows.Count, cVntTarget).End(xlUp).Row + 1
End With
lngSource = .Cells(.Rows.Count, cVntSource).End(xlUp).Row
objTarget.Cells(lngTarget, cVntTarget) _
= .Cells(lngSource, cVntSource).Value
.Parent.Close False
End With
End If
Next
End Sub
'*******************************************************************************
РЕДАКТИРОВАТЬ:
Sub CopyCellFromWorkbooksEDIT()
' Source Folder Path
Const cStrPath As String = _
"C:\"
' Source Worksheet Name/Index
Const cStrSource As Variant = "financial_report"
Const cVntSource As Variant = "Y" ' Source Column Letter/Number
' Target Worksheet Name/Index
Const cStrTarget As Variant = "Sheet1"
Const cVntTarget As Variant = 1 ' Target Column Letter/Number
' FSO Objects
Dim objFSO As Object, objFolder As Object, objFile As Object
Dim objTarget As Worksheet ' Target Worksheet (ThisWorkbook)
Dim lngTarget As Long ' Target Column
Dim lngSource As Long ' Source Column
Set objFSO = CreateObject("Scripting.FileSystemObject")
Set objFolder = objFSO.GetFolder(cStrPath)
Set objTarget = ThisWorkbook.Sheets(cStrTarget)
For Each objFile In objFolder.Files
If objFSO.GetExtensionName(objFile.Name) = "xls" Then
With Workbooks.Open(objFile.Path).Worksheets(cStrSource)
With objTarget
lngTarget = _
.Cells(.Rows.Count, cVntTarget).End(xlUp).Row + 1
End With
lngSource = .Cells(.Rows.Count, cVntSource).End(xlUp).Row
objTarget.Cells(lngTarget, cVntTarget) _
= .Cells(2, 7).Value ' (G2)
objTarget.Cells(lngTarget, cVntTarget + 1) _
= .Cells(lngSource, cVntSource).Value
.Parent.Close False
End With
End If
Next
End Sub
'*******************************************************************************