将单元格从excel表复制到另一个excel电子表格

时间:2020-01-13 00:59:19

标签: excel vba

这听起来可能令人困惑,所以我会尽力解释。我真的是VBA的新手,我擅长excel。我正在尝试制作一个将某些值填充到另一个设置为模板的电子表格中的电子表格。但是,有多个不同的模板,但根据找到的值需要填写。模板是单独的文件。在无法提供客户业务信息的情况下,我将使用一个示例。我有模板a.xls,b.xls和c.xls,其中有3个单元格需要设置电子表格中的信息,即表中的result1,result2,result3。因此,如果找到“ a”,则取result1,result2和result3并将其复制并粘贴到a.xls require单元格中。

table

我目前拥有的代码在“数据”列中找到值,并仅返回一个msgbox。我不知道这是否是正确的解决方法,而且我在网上浏览示例,所以任何帮助都很棒。

到目前为止,这是我的代码。

    Sub LookupTableValue()
Dim Table2 As ListObject
Dim FoundCell1, FoundCell2 As Range
Dim LookupValue1, LookupValue2 As String
  LookupValue1 = "a"
  LookupValue2 = "b"
  Set Table2 = ActiveSheet.ListObjects("Table2")
    Set FoundCell1 = Table2.DataBodyRange.Columns(1).Find(LookupValue1, LookAt:=xlWhole)
    Set FoundCell2 = Table2.DataBodyRange.Columns(1).Find(LookupValue2, LookAt:=xlWhole)
    If Not (FoundCell1 Is Nothing) Then
        If FoundCell1.Value = LookupValue1 Then
            MsgBox "Found a"
        End If
    End If
    If Not (FoundCell2 Is Nothing) Then
        If FoundCell2.Value = LookupValue2 Then
            MsgBox "Found b"
        End If
    End If
End Sub

所以我想我想要代替MsgBox行的是打开特定的xls电子表格,该电子表格是模板,然后将表格中的单元格复制到此模板中,然后在另一个文件夹中另存为新的.xls。

1 个答案:

答案 0 :(得分:0)

Pathname=File Path
If FoundCell1.Value = LookupValue1 Then
            MsgBox "Found a"
            Filename=File name depending on the value
            Set workbook = Workbooks.Open(Filename:=Pathname & Filename)
            Copy table content to above workbook. See this [https://stackoverflow.com/questions/31702885/copy-tables-to-another-worksheet][1]
            workbook.SaveAs Filename:=NewFileName, FileFormat:=xlWorkbookNormal
End If

希望这会对您有所帮助。