[英]How to Link Contents from Contents in an Excel workbook to another Excel workbook using VBA?
I have built a VBA code that links cell contents from one Excel sheet Employee Form
to another worksheet Employee Database
in the same workbook as below. 我建立了一个VBA代码,该代码将单元格内容从一个Excel工作表
Employee Form
到同一工作簿中的另一个工作表Employee Database
,如下所示。
Sub Submit_Form()
Dim LastRow As Long, ws As Worksheet
Set ws = Sheets("Employee Database")
LastRow = ws.Range("A" & Rows.Count).End(xlUp).Row + 1
ws.Range("A" & LastRow).Value = Worksheets("Employee Form").Range("D7").Value
....
ws.Range("Z" & LastRow).Value = Worksheets("Employee Form").Range("AB").Value
End Sub
The code works well, but how to modify the code now that these sheets are in separate Excel files? 该代码运行良好,但是既然这些工作表位于单独的Excel文件中,那么如何修改代码? The new Excel files are the same as the respective names of these worksheets.
新的Excel文件与这些工作表的相应名称相同。
Thanks! 谢谢!
We could try to code below: 我们可以尝试下面的代码:
Sub connect() ' ' connect Macro ' 子connect()''连接宏'
'
ActiveWorkbook.Queries.Add Name:="Sheet1", Formula:= _
"let" & Chr(13) & "" & Chr(10) & " Source = Excel.Workbook(File.Contents(""D:\Try\write.xlsx""), null, true)," & Chr(13) & "" & Chr(10) & " Sheet1_Sheet = Source{[Item=""Sheet1"",Kind=""Sheet""]}[Data]," & Chr(13) & "" & Chr(10) & " #""Changed Type"" = Table.TransformColumnTypes(Sheet1_Sheet,{{""Column1"", Int64.Type}})" & Chr(13) & "" & Chr(10) & "in" & Chr(13) & "" & Chr(10) & " #""Changed Type"""
Sheets.Add After:=ActiveSheet
With ActiveSheet.ListObjects.Add(SourceType:=0, Source:= _
"OLEDB;Provider=Microsoft.Mashup.OleDb.1;Data Source=$Workbook$;Location=Sheet1;Extended Properties=""""" _
, Destination:=Range("$A$1")).QueryTable
.CommandType = xlCmdSql
.CommandText = Array("SELECT * FROM [Sheet1]")
.RowNumbers = False
.FillAdjacentFormulas = False
.PreserveFormatting = True
.RefreshOnFileOpen = False
.BackgroundQuery = True
.RefreshStyle = xlInsertDeleteCells
.SavePassword = False
.SaveData = True
.AdjustColumnWidth = True
.RefreshPeriod = 0
.PreserveColumnInfo = False
.ListObject.DisplayName = "Sheet1"
.Refresh BackgroundQuery:=False
End With
Selection.ListObject.QueryTable.Refresh BackgroundQuery:=False
End Sub
You can also link to another worksheet by doing an action: Connect to another workbook 您也可以通过执行以下操作链接到另一个工作表: 连接到另一个工作簿
Hope that helps! 希望有帮助!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.