读取.xlsx文件并将内容复制到另一个工作簿

时间:2013-06-07 04:35:23

标签: excel-vba copy excel-2010 vba excel

我正在尝试读取一个Excel文件的内容并将其复制到另一个工作簿中。这是我尝试的代码,但它不起作用:

Const strPath As String = "C:\Users\Excel\Book2.xlsx"

Sub Sample()
    Dim ws As Worksheet
    Dim MyData As String, strData() As String
    Dim WriteToRow As Long, i As Long
    Dim strCurrentTxtFile As String
    Dim xlExcelApp  As Excel.Application
    Dim xlImportWorkbook As Excel.Workbook
    Dim xlManRange As Excel.Range

    Set ws = Sheets("Sheet1")

    '~~> Start from Row 1
    WriteToRow = 1

    strCurrentTxtFile = Dir(strPath & "*.xlsx")

    '~~> Looping through all text files in a folder
    Do While strCurrentTxtFile <> ""

        '~~> Open the file in 1 go to read it into an array
        Set xlExcelApp = New Excel.Application
        Set xlImportWorkbook = xlExcelApp.Workbooks.Open(strPath)
        Set xlManRange = xlImportWorkbook.Worksheets(Sheet1).Range("A1:A20")

        MyData = Space$(LOF(1))
        Get #1, , MyData
        Close #1

        strData() = Split(MyData, vbCrLf)

        '~~> Read from the array and write to Excel
        For i = LBound(strData) To UBound(strData)
            ws.Range("A" & WriteToRow).Value = strData(i)
            WriteToRow = WriteToRow + 1
        Next i

        strCurrentTxtFile = Dir
    Loop
End Sub

请帮我解决这个问题。

0 个答案:

没有答案