excel 我在使用www.example.com中的Range.PasteSpecial()方法时遇到问题VB.net

bvuwiixz  于 2022-11-18  发布在  .NET
关注(0)|答案(1)|浏览(169)

我需要将一些数据从一个Excel工作簿复制到另一个工作簿,但我只需要复制值和格式。除了使用PasteSpecial()方法,我不知道还有其他方法可以完成此操作。问题是,当我运行代码时,我收到以下错误消息:

System.Runtime.InteropServices.COMException: 'Microsoft Excel cannot paste the data.'

这是我目前使用的代码:

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

我试着这样做:

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

但这对我不起作用,因为即使最后一段代码确实将值复制到了新工作表上,我仍然缺少格式。

58wvjzkj

58wvjzkj1#

今天我解决了这个问题。问题不在于PasteSpecial方法本身,而在于我试图通过OpenFileDialog将区域粘贴到一个预先存在的工作簿中。
我不知道为什么会发生这种情况,因为在VBA中,我使用类似的代码打开一个预先存在的工作簿,从来没有任何问题。虽然现在我想起来了,在VBA中,我没有使用文件对话框打开工作簿。我使用的是Worbooks.Open(),它会导致一些问题,因为用户会将我试图打开的文件移动到PC中的不同位置。
无论如何,我现在创建一个新的Excel文件,并将数据粘贴到那里,如下所示:

Sub CopyData()

    Dim xlApp As New Excel.Application
    Dim xlWb As Excel.Workbook
    Dim wsActvSh As Worksheet = Globals.ThisWorkbook.ActiveSheet
    Dim strLiquidacion As String = Globals.shTbClientes.Range("b:b").Find(Mid(wsActvSh.Name, 1, 3)).Offset(0, 1).Value
    Dim xlWbActSh As Worksheet

    xlApp.DisplayAlerts = False
    xlWb = xlApp.Workbooks.Add()
    xlApp.Visible = True

    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)
            xlWbActSh = xlWb.ActiveSheet
            xlWbActSh.Range("a:i").PasteSpecial(XlPasteType.xlPasteValues)
            xlWbActSh.Range("a:i").PasteSpecial(XlPasteType.xlPasteFormats)
        End If
    Next

End Sub

相关问题