将数据从不同的工作簿复制到当前工作表

我基本上卡住了。 我有一个代码,允许我浏览一个文件,一旦文件被选中,它将复制该文件中的所有数据,然后允许我从当时打开的任何工作簿中select一个工作表。 一旦工作表被选中[这是我卡住了]我想它将其粘贴到j7。 相反,它不这样做,考虑到我将每天更改文件名称,因为它具有当前的datedate。 这里是我的代码:

Sub Macro4() ' ' Macro4 Macro ' ' Range("A1").Select Dim fileStr As String fileStr = Application.GetOpenFilename() If fileStr = "False" Then Exit Sub Workbooks.Open fileStr Range("A2").Select Range(Selection, Selection.End(xlToRight)).Select Range(Selection, Selection.End(xlDown)).Select Selection.Copy Window.Sheets(Array("Forecast_workings")).Select{**this is where i want to be able to select a worksheet from any open workbook and it will paste the data in cell J7 of that worksheet.** Range("J7").Select Application.CutCopyMode = False Range("C16:C27").Select Selection.Copy Range("E16").Select ActiveSheet.Paste Application.CutCopyMode = False Range("G16:G27").Select Selection.Copy Range("C16").Select ActiveSheet.Paste Application.CutCopyMode = False Range("O16").Select End Sub 

我可以在代码中看到很多错误。

首先是事情。 您避免使用.Select 。 有趣的阅​​读

如果我正确地理解了你,那么要得到用户在运行时select的工作表名称,可以使用Application.InputBox Type:=8 Application.InputBox 。 这将返回一个范围,您可以使用.Parent.Name来获取工作表的名称。

这是你正在尝试?

你的代码可以写成( UNTESTED

 Sub Macro4() Dim fileStr As String Dim wb As Workbook, thiswb As Workbook Dim ws As Worksheet, thisws As Worksheet Dim Lcol As Long, LRow As Long Dim Ret As Range '~~> Set an object for thisworkbook and worksheet Set thiswb = ThisWorkbook '~~> Change this to the sheet from where you want to copy Set thisws = thiswb.Sheets("Sheet1") '~~> Let user choose a file fileStr = Application.GetOpenFilename() If fileStr = "False" Then Exit Sub '~~> Set an object for workbook opened and it's worksheet Set wb = Workbooks.Open(fileStr) On Error Resume Next Set Ret = Application.InputBox("Select a cell from the sheet you want to choose", Type:=8) On Error GoTo 0 If Ret Is Nothing Then Exit Sub Set ws = wb.Sheets(Ret.Parent.Name) With thisws '~~> Find Last column in row 2 Lcol = .Cells(2, .Columns.Count).End(xlToLeft).Column '~~> Find last cell in Col 1 LRow = .Range("A" & .Rows.Count).End(xlUp).Row '~~> Copy your range directly to new worksheet selected .Range(.Cells(2, 1), .Cells(LRow, Lcol)).Copy ws.Range("J7") .Range("C16:C27").Copy ws.Range("E16") .Range("G16:G27").Copy ws.Range("C16") Application.CutCopyMode = False End With End Sub 

当使用多个工作簿时,不要使用range(),而使用wb.range(),其中wb是使用set函数定义的。 另外activesheet可能会很棘手。 最好命名您使用工作表(“无论”)的工作表。 最后,要复制的东西不使用激活/select,只是这样做:

 wb.sheets("whatever").range() thisworkbook.sheets("watever2").range(""). 

我也看到你不使用application.enableevents = false / true,所以事件会像疯了一样触发,如果在worksheet_change部分有代码,你的activesheet(或cell)将会变得像疯了似的。