使用Excel VBA将多个电子表格有效地导入到一个主表中

时间:2018-07-30 14:13:45

标签: excel vba excel-vba

我是VBA的新手,我已经编写了一些代码,尽管它可以正常工作,但我认为它很庞大,如果需要进行更改,效果不是很好。

代码打开电子表格,运行一个函数(称为“ LastRow”)以复制数据,并运行另一个函数(称为“ NxtRow”)以将其粘贴到带有宏的电子表格的下一个空行中,然后关闭数据已复制并移至下一个。基本上是将多张纸串联在一起。

我认为必须有一种方法来编写代码,以一次调用函数,然后循环遍历列表中的每个工作表。这可能吗?

我的代码是:

NxtRow()函数

<Dropdown
                data={this.state.data}
                label='Select'
                selectedItemColor='#2872c0'
                fontSize={15}
                valueExtractor={({ displayName }) => displayName}
                itemPadding={10}
                onChangeText={() => console.log(this.onChangeText)}
                /> 

LstRow()函数

Public Function NxtRow()
Dim BlankRow As Long
Windows("GA_BudgetTool_MASTER.xlsm").Activate
BlankRow = Range("A" & Rows.Count).End(xlUp).Row + 1
Cells(BlankRow, 1).Select
ActiveSheet.Paste
BlankRow = Range("A" & Rows.Count).End(xlUp).Row + 1
Cells(BlankRow, 1).Select
End Function

VBA Sub()

Public Function LastRow()
Dim LstRow As Long, LstCol As Long, Rng As Range, A3 As Range
LstRow = Range("A" & Rows.Count).End(xlUp).Row
LstCol = Range("O" & LstRow).Column
Set Rng = Range(Cells(LstRow, 1), Cells(LstRow, LstCol))
Set A3 = Range("A3")
Range(A3, Rng).Select
Selection.Copy
End Function

以这种方式进行约30张纸。有没有更简单的方法可以编写此代码,并在以后需要时更轻松地进行修改?

1 个答案:

答案 0 :(得分:1)

我只需要对文件名进行一些排列,然后使用for循环将函数调用重复多次即可

Sub ImpData()

    'Deactivate Screen Updating and Display Alerts
    With Application
        .ScreenUpdating = False
        .DisplayAlerts = False
    End With

    Dim filenames As Variant
    filenames = Array("file1", "file2")

    For i = 1 To UBound(filenames) + 1
        Workbooks.Open Filename:=filenames(i - 1)
        LastRow
        NxtRow
        Windows("Worksheet" & i & ".xlsx").Activate
        ActiveWindow.Close
    Next i

    'Reactivate Screen Updating and Display Alerts
    With Application
        .ScreenUpdating = True
        .DisplayAlerts = True
    End With

End Sub
相关问题