我有两个打开的工作簿,即工作簿A和工作簿B.我需要将数据列从特定工作表A从工作簿A传输到工作簿B中的特定工作表。
示例数据:
-26.32
-20.56
-44.93
-26.64
-45.99
-40.76
-34.21
-25.54
-48.63
2.966
9.163
4.879
5.01
11.48
16.19
16.19
如何创建将此工作簿从工作簿A传输到工作簿B的程序?工作簿A也可以是任何打开的工作簿。当该程序再次运行时,它可能不是同一个文件。提前谢谢。
当前代码:
Sub Sample()
Dim wbA As Workbook, wbB As Workbook
Dim filepath As String
Set wbA = ThisWorkbook 'you say the current workbook
filepath = Application.GetOpenFilename("Excel Files (*.xlsx), *.xlsx", , , , False)
Set wbB = Workbooks.Open(filepath)
With wbA
.Sheets("Results").Range("A1").Copy wbB.Sheets("Sheet1").Range("A1")
End With
End Sub
选择来源和目标工作簿:
Sub Sample()
Dim wbA As Workbook, wbB As Workbook
Dim filepath As String
filepath = Application.GetOpenFilename("Excel Files (*.xlsx), *.xlsx", , , , False)
Set wbA = Workbooks.Open(filepath)
filepath = Application.GetOpenFilename("Excel Files (*.xlsx), *.xlsx", , , , False)
Set wbB = Workbooks.Open(filepath)
With wbA
.Sheets("Sheet1").Range("A1:A3").Copy wbB.Sheets("Sheet1").Range("A1:A3")
End With
End Sub
答案 0 :(得分:0)
试试这个:
Sub Sample()
Dim wbA as Workbook, wbB as Workbook
Dim filepath as String
Set wbA = Thisworkbook 'you say the current workbook
filepath = "C:\User\UserName\Documents\Myworkbook.xlsx" 'hard coded version
Set wbB = Workbooks.Open(filepath)
With wbB
.Sheets("your sheet name here").Range("your range here").Copy _
wbA.Sheets("destination sheet here").Range("destination range here")
End With
End Sub
如果您要选择文件,请使用以下行:
filepath = Application.GetOpenFilename("Excel Files (*.xlsx), "*.xlsx",,,,False) 'open file dialog version
然后你必须从该位置选择文件 希望这有点帮助。
编辑1:试试这个
filepath = Application.GetOpenFilename(filefilter:="Excel Files (*.xlsx), "*.xlsx") 'open file dialog version
答案 1 :(得分:0)
这次谈话太晚了。我知道。但是..... 似乎他在问如何将数据从一个打开的工作簿发送到另一个打开的工作簿。上面的所有答案都包含让他“打开”工作簿的代码。所以我明白混乱的来源。工作簿已打开。再次尝试打开它会导致错误消息。
对于将来寻求相同建议的任何人 - 要引用已经打开的工作簿,您只需使用它的名称和扩展名:WorkBooks("openWorkBookName.xlsx")
无需引用文件的文件夹或目录位置。
Sub setVariableToAnotherALREADYopenWB()
Dim anotherOpenWorkbook As Workbook
Dim ws2 As Worksheet
' The Full File Location/Folder/Directory is not necessary
' when referring to another open workbook
'
' Just use the name of the workbook and it's extension
Set anotherOpenWorkbook = Workbooks("Phone Dir.xlsx")
Set ws2 = anotherOpenWorkbook.Worksheets(1)
ThisWorkbook.Worksheets("Office Phone Directory").Range("A12:A39").Copy _
Destination:=ws2.Range("A1")
Set anotherOpenWorkbook = Nothing
Set ws2 = Nothing
End Sub