我需要从多个工作簿和多个工作表中复制并粘贴数据。 (名称不断更改工作表和工作簿)
我有一个代码,但是在这里我需要手动选择单元格。我只想选择工作表,它应该自动将工作表中的所有数据导入工作簿中的指定工作表。那可能吗?
Sub ImportDatafromotherworksheet()
Dim wkbCrntWorkBook As Workbook
Dim wkbSourceBook As Workbook
Dim rngSourceRange As Range
Dim rngDestination As Range
Set wkbCrntWorkBook = ActiveWorkbook
With Application.FileDialog(msoFileDialogOpen)
.Filters.Clear
.Filters.Add "Excel 2007-13", "*.xlsx; *.xlsm; *.xlsa"
.AllowMultiSelect = False
.Show
If .SelectedItems.Count > 0 Then
Workbooks.Open .SelectedItems(1)
Set wkbSourceBook = ActiveWorkbook
Set rngSourceRange = Application.InputBox(prompt:="Select source range", Title:="Source Range", Default:="A1", Type:=8)
wkbCrntWorkBook.Activate
Set rngDestination = Application.InputBox(prompt:="Select destination cell", Title:="Select Destination", Default:="A1", Type:=8)
rngSourceRange.Copy rngDestination
rngDestination.CurrentRegion.EntireColumn.AutoFit
wkbSourceBook.Close False
End If
End With
End Sub
答案 0 :(得分:1)
这是一个简单的示例,您可以从一个复制到另一个。让我知道您是否需要更具体的帮助。
Sub testing()
Dim des_wb As Workbook, sou_wb As Workbook
Dim des_ws As Worksheet
Dim sou_rng As Range
ChDir (ActiveWorkbook.Path)
Set des_wb = ActiveWorkbook
Set sou_wb = Workbooks.Open(Application.GetOpenFilename)
Set sou_ws = sou_wb.Worksheets(1)
Set sou_rng = sou_ws.Range("A1").CurrentRegion
sou_rng.Copy
des_wb.Worksheets(1).Range("A1").PasteSpecial
End Sub
答案 1 :(得分:0)
您可以使用“源”范围来获取其Parent
表UsedRange
,如下所示:
Sub ImportDatafromotherworksheet()
Dim wkbCrntWorkBook As Workbook
Dim rngSourceRange As Range
Dim rngDestination As Range
Set wkbCrntWorkBook = ActiveWorkbook
With Application.FileDialog(msoFileDialogOpen)
.Filters.Clear
.Filters.Add "Excel 2007-13", "*.xlsx; *.xlsm; *.xlsa"
.AllowMultiSelect = False
.Show
If .SelectedItems.Count > 0 Then
With Workbooks.Open(.SelectedItems(1)) ' open and reference current selected "source" workbook
Set rngSourceRange = Application.InputBox(prompt:="Select any cell in the wanted sheet ", Title:="Source sheet chosing", Default:="A1", Type:=8) ' have user select any cell in source sheet
If Not rngSourceRange Is Nothing Then ' if any valid "source" range selected
wkbCrntWorkBook.Activate ' this could be omitted since subsequent InputBox allowa user to switch between open workbooks
Set rngDestination = Application.InputBox(prompt:="Select destination cell", Title:="Select Destination", Default:="A1", Type:=8) ' have user select "destination" cell
If Not rngDestination Is Nothing Then ' if any valid "destination" range selected
rngSourceRange.Parent.UsedRange.Copy rngDestination.Cells(1, 1) ' be sure to collapse "destination" range to a single cell
rngDestination.CurrentRegion.EntireColumn.AutoFit
End If
End If
.Close False ' close referenced (i.e. current "source" sheet) sheet
End With
End If
End With
End Sub