我是VBA的新手。我正在处理一个文件,需要从另一个文件中复制数据,该文件位于不同的文件夹中。
Folder 1 --> Main File---> Dashboard
至Folder 2 --> Calculations---> Master File
现在宏将从"仪表板"执行。工作表和数据将从"主文件"并粘贴在"仪表板"。
我尝试了很少的代码,但他们没有帮助。
请帮帮我。
答案 0 :(得分:0)
这是我使用的通用复制值宏,希望能让你走上正确的道路。
Sub TransferData()
'transfer stuff from workbook 1 to workbook 2
Dim strPath1 As String
Dim strPath2 As String
Dim wbkWorkbook1 As Workbook
Dim wbkWorkbook2 As Workbook
'define paths and filenames
strPath1 = "C:\take from this.xlsx"
strPath2 = "C:\put in this.xlsx"
'open files
Set wbkWorkbook1 = Workbooks.Open(strPath1)
Set wbkWorkbook2 = Workbooks.Open(strPath2)
'copy the values across
wbkWorkbook2.Worksheets("Sheet1").Range("A1:B3").Value = _
wbkWorkbook1.Worksheets("Sheet1").Range("A1:B3").Value
'close the two workbooks
wbkWorkbook1.Close (False)
wbkWorkbook2.Close (True)
End Sub
修改强>
由于您将工作簿1设置为运行vba的工作簿,因此在上面您将收到错误,因为工作簿1确实已经打开。
尝试以下代码将数据值从“此工作簿”传输到工作簿2:
Sub TransferDataV2()
'transfer stuff from this workbook to workbook 2
Dim strPath2 As String
Dim wbkWorkbook1 As Workbook
Dim wbkWorkbook2 As Workbook
'define paths and filenames
strPath2 = "C:\put in this.xlsx"
'open files
Set wbkWorkbook1 = ThisWorkbook '### changed this
Set wbkWorkbook2 = Workbooks.Open(strPath2)
'copy the values across
'### change the sheet and range to what you need
wbkWorkbook2.Worksheets("Sheet2").Range("A1:B3").Value = _
wbkWorkbook1.Worksheets("Sheet1").Range("A1:B3").Value
'close the workbook
wbkWorkbook2.Close (True)
End Sub