我构建了一个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
代码运行良好,但是既然这些工作表位于单独的Excel文件中,那么如何修改代码? 新的Excel文件与这些工作表的相应名称相同。
谢谢!
答案 0 :(得分:0)
我们可以尝试在下面进行编码:
子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
您还可以通过执行以下操作链接到另一个工作表: Connect to another workbook
希望有帮助!