Excel vba将多张工作表导入单张工作表并保留格式

时间:2016-12-11 11:34:52

标签: excel vba excel-vba

我是vba的全新人物。 我已设法将其他工作簿中的多张工作表导入一张工作表。 但我想保持格式,并保持导入单元格的颜色。 这是我的代码:

Public strFileName As String
Public currentWB As Workbook
Public dataWB As Workbook
Public strCopyRange As String

Sub delData() 'Clears MasterData except 1st line
Dim ws As Worksheet
For Each ws In Worksheets
    Select Case ws.Name
    Case Is = "List", "Sheet1"
        ' Do Nothing
    Case Else
        ws.UsedRange.Offset(1).ClearContents


    End Select
Next ws
End Sub

Sub GetData()
Dim strWhereToCopy As String, strStartCellColName As String
Dim strListSheet As String

strListSheet = "List"

On Error GoTo ErrH
Sheets(strListSheet).Select
Range("B2").Select

'this is the main loop, we will open the files one by one and copy their data into the masterdata sheet
Set currentWB = ActiveWorkbook
Do While ActiveCell.Value <> ""

    strFileName = ActiveCell.Offset(0, 1) & ActiveCell.Value
    strCopyRange = ActiveCell.Offset(0, 2) & ":" & ActiveCell.Offset(0, 3)
    strWhereToCopy = ActiveCell.Offset(0, 4).Value
    strStartCellColName = Mid(ActiveCell.Offset(0, 5), 2, 1)

    Application.Workbooks.Open strFileName, UpdateLinks:=False, ReadOnly:=True
    Set dataWB = ActiveWorkbook

    Range(strCopyRange).Select
    Selection.Copy

    currentWB.Activate
    Sheets(strWhereToCopy).Select
    lastRow = LastRowInOneColumn(strStartCellColName)
    Cells(lastRow + 1, 1).Select

    Selection.PasteSpecial xlPasteValues, xlPasteSpecialOperationNone
    Application.CutCopyMode = False
    dataWB.Close False
    Sheets(strListSheet).Select
    ActiveCell.Offset(1, 0).Select
Loop
Exit Sub


ErrH:
    MsgBox "It seems some file was missing. The data copy operation is not complete."
Exit Sub


End Sub

Public Function LastRowInOneColumn(col)
    'Find the last used row in a Column: column A in this example
    Dim lastRow As Long
    With ActiveSheet
    lastRow = .Cells(.Rows.Count, col).End(xlUp).Row
    End With
    LastRowInOneColumn = lastRow
End Function

我的函数GetData()不会覆盖现有数据 - 所以我做了一个变通方法并创建了函数delData()。如何使GetData函数覆盖现有数据? 我想保留我导入的纸张的格式和颜色。这也应该覆盖旧的数据/颜色。

我真的希望这对某人有意义:o) 任何建议都是最令人沮丧的 感谢...

1 个答案:

答案 0 :(得分:0)

使用:

Selection.PasteSpecial Paste:=xlPasteFormats, Operation:=xlNone, _
        SkipBlanks:=False, Transpose:=False

而不是Selection.PasteSpecial xlPasteValues, xlPasteSpecialOperationNone