I need to copy some data from one Excel workbook to another but I only need to copy values and formats. I don't know any other way of doing this but to use the PasteSpecial() method. The problem is that when I run the code I get this error message:
System.Runtime.InteropServices.COMException: 'Microsoft Excel cannot paste the data.'
This is the code I am using at the moment:
Sub CopyData()
Dim xlApp As New Excel.Application
Dim xlWb As Excel.Workbook
xlApp.DisplayAlerts = False
Dim xlFileName As String
Dim OpenFile As New OpenFileDialog
If OpenFile.ShowDialog() <> DialogResult.Cancel Then
xlFileName = OpenFile.FileName
xlWb = xlApp.Workbooks.Open(xlFileName)
Else
xlApp.Quit()
Exit Sub
End If
xlApp.Visible = True
For Each xlWs As Worksheet In xlWb.Worksheets
If xlWb.Worksheets.Count > 1 Then
xlWs.Delete()
End If
Next
Dim wsActvSh As Worksheet = Globals.ThisWorkbook.ActiveSheet
For Each ws As Worksheet In Globals.ThisWorkbook.Worksheets
If ws.Visible = True And Mid(ws.Name, 5, 2) = Mid(wsActvSh.Name, 11, 2) Then
ws.Range("a:i").Copy()
xlWb.Worksheets.Add().Name = Mid(ws.Name, 5)
xlWb.ActiveSheet.Range("a1").PasteSpecial(XlPasteType.xlPasteValues)
End If
Next
End Sub
I tried doing this:
For Each ws As Worksheet In Globals.ThisWorkbook.Worksheets
If ws.Visible = True And Mid(ws.Name, 5, 2) = Mid(wsActvSh.Name, 11, 2) Then
xlWb.Worksheets.Add().Name = Mid(ws.Name, 5)
xlWb.ActiveSheet.Range("a:i").Value = ws.Range("a:i").Value
End If
Next
But this doesn't work for me because even though the last code does copy the values onto the new worksheet, I am still missing the formats.