Excel VBA - 根据列名复制数据

时间:2017-04-13 17:34:49

标签: excel-vba runtime-error copy-paste vba excel

我遇到了一个问题:使用三个单独的工作表(源1,源2,模板)我必须从源文件中获取数据并将其粘贴到模板上,具体取决于列名称。 即来源1的前三列'名称与模板上的名称匹配,模板的第四行与第四行匹配,第二行匹配源2的第四行。

这是我到目前为止所得到的(它是不完整的)。 检查其他线程我做了一个"派生"一个例子,但我仍然无法使它工作。我在Copy_Columns()

中标有注释的行上遇到运行时错误9
Sub MasterCopy()

    Open_Files
    Copy_Columns

End Sub

Sub Open_Files()
    Application.Workbooks.Open Filename:="C:Source 1.xls"
    Application.Workbooks.Open Filename:="C:Source 2.xls"
    Application.Workbooks.Open Filename:="C:Template.xls"
End Sub

Sub Copy_Columns()

    Dim Source1 As Worksheet
    Source1 = Application.Workbooks("C:Source 1.xls").Worksheets("Sheet1") 'here is where the error appears
    Source1.Select

    Dim columnToBeCopied As Integer
    columnToBeCopied = getColumnName("Source1", "columnToBeCopied")

    Dim template As Worksheet
    template = Application.Workbooks("C:Template.xls").Worksheets("Data")
    template.Activate

    Dim columnToBePasted As Integer
    columnToBePasted = getColumnName("template", "columnToBePasted")

    Sheets("Source1").Columns(columnToBeCopied).Copy Sheets("template").Columns(columnToBePasted)

End Sub

Public Function getColumnName(ByVal sheetName As String, ByVal columnName As String)

    Dim lastColumn As Integer
    lastColumn = ActiveSheet.Cells(Rows.Count, "A").End(xlUp).Column

    Dim iterator As Integer
    iterator = 0
    While (iterator <= lastColumn)
        If (LCase(Sheets(sheetName).Range(1, iterator)) = LCase(columnName)) Then
            getColumnName = iterator
        Else: iterator = iterator + 1
        End If
    Wend
    If IsEmpty(getColumnName) Then getColumnName = 0

End Function

有一些有些接近的例子,但它们要么太复杂(这是我第一次使用VBA),要么太模糊&#34;模糊&#34;他们使用a,o,x,b作为变量名称...... 任何帮助非常感谢:)

1 个答案:

答案 0 :(得分:1)

将带有错误的行更改为:

File[] files = fileCollection.compressAllQuitely(); intent.putExtra(RESULT_FILES, files);