Чтобы добавить данные из другого файла с помощью Excel VBA, вы можете использовать несколько методов. Вот три часто используемых подхода с примерами кода:
- Использование метода Workbooks.Open:
Этот метод открывает исходный файл, копирует данные из нужного диапазона и вставляет их в целевую книгу.
Sub AddDataFromAnotherFile_Method1()
Dim sourceWB As Workbook
Dim targetWB As Workbook
Dim sourceWS As Worksheet
Dim targetWS As Worksheet
' Open the source workbook
Set sourceWB = Workbooks.Open("C:\Path\to\SourceFile.xlsx")
Set sourceWS = sourceWB.Worksheets("Sheet1")
' Open the target workbook
Set targetWB = ThisWorkbook ' Assumes the code is in the target workbook
Set targetWS = targetWB.Worksheets("Sheet1")
' Copy data from the source worksheet to the target worksheet
sourceWS.Range("A1:D10").Copy targetWS.Range("A1")
' Close the source workbook without saving changes
sourceWB.Close SaveChanges:=False
End Sub
- Использование нотации Workbooks(“FileName”).Sheets(“SheetName”):
Этот метод напрямую ссылается на исходную книгу и лист для копирования данных.
Sub AddDataFromAnotherFile_Method2()
Dim sourceWB As Workbook
Dim targetWB As Workbook
Dim sourceWS As Worksheet
Dim targetWS As Worksheet
' Reference the source workbook and worksheet
Set sourceWB = Workbooks("SourceFile.xlsx")
Set sourceWS = sourceWB.Sheets("Sheet1")
' Reference the target workbook and worksheet
Set targetWB = ThisWorkbook ' Assumes the code is in the target workbook
Set targetWS = targetWB.Sheets("Sheet1")
' Copy data from the source worksheet to the target worksheet
sourceWS.Range("A1:D10").Copy targetWS.Range("A1")
End Sub
- Использование метода Application.GetOpenFilename:
Этот метод предлагает пользователю выбрать исходный файл, а затем копировать данные.
Sub AddDataFromAnotherFile_Method3()
Dim sourceFile As Variant
Dim sourceWB As Workbook
Dim targetWB As Workbook
Dim sourceWS As Worksheet
Dim targetWS As Worksheet
' Prompt the user to select the source file
sourceFile = Application.GetOpenFilename("Excel Files (*.xlsx), *.xlsx")
' Check if a file was selected
If sourceFile <> False Then
' Open the source workbook
Set sourceWB = Workbooks.Open(sourceFile)
Set sourceWS = sourceWB.Worksheets("Sheet1")
' Open the target workbook
Set targetWB = ThisWorkbook ' Assumes the code is in the target workbook
Set targetWS = targetWB.Worksheets("Sheet1")
' Copy data from the source worksheet to the target worksheet
sourceWS.Range("A1:D10").Copy targetWS.Range("A1")
' Close the source workbook without saving changes
sourceWB.Close SaveChanges:=False
End If
End Sub