从vb.net中删除Excel工作表中的换行符

时间:2014-05-20 10:04:20

标签: vb.net excel-interop

我想通过vb.net打开一个excel文件并删除所选工作表的所有换行符。我试图做的是:

Imports Microsoft.Office.Interop
Imports Microsoft.Office.Interop.Excel

Public Class MyExcel
    Private _xlsheetRelevant As Excel.Worksheet
    Private _xlApp As Excel.Application
    Private _xlworkbook As Excel.Workbook
    Public Shared _shxlworkbook As Excel.Workbook

Public Sub New()
    Try
        _xlApp = CType(GetObject(, "Excel.Application"), Excel.Application)
    Catch e As Exception
        _xlApp = CType(CreateObject("Excel.Application"), Excel.Application)
    End Try
    _xlApp.Visible = True
End Sub

Public Sub OpenFile(ByVal FilenameL As String)
    _xlApp.Workbooks.Open(FilenameL, ReadOnly:=False)
    _xlworkbook = DirectCast(_xlApp.ActiveWorkbook, Excel.Workbook)
    _shxlworkbook = _xlworkbook
    _xlApp.Calculation = XlCalculation.xlCalculationManual
End Sub

Public Sub RemoveLinebreaks()
    _xlsheetRelevant = DirectCast(_xlworkbook.Worksheets("Tabelle1"), Excel.Worksheet)
    _xlsheetRelevant.Cells.Replace(What:=Chr(10), Replacement:="", LookAt:=2, SearchOrder:=1, MatchCase:=False, SearchFormat:=False, ReplaceFormat:=False)
    End Sub
End Class

Public Class Form1
    Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
        Dim ExcelV As New MyExcel
        ExcelV.OpenFile("C:\Users\xxx\Desktop\Mappe1.xlsx")
        ExcelV.RemoveLinebreaks()
    End Sub
End Class

我总是收到以下消息:

  

Microsoft Excel无法找到要替换的任何数据。检查您的搜索   格式和标准是正确定义的。如果你确定的话   匹配数据存在于此工作簿中,它可能位于受保护的工作表中。   Excel无法替换受保护工作表上的数据。

任何想法,我做错了什么?

2 个答案:

答案 0 :(得分:2)

自己找到解决方案:

_xlsheetRelevant.Cells.WrapText = False

而不是

_xlsheetRelevant.Cells.Replace(What:=Chr(10), Replacement:="", LookAt:=2, SearchOrder:=1, MatchCase:=False, SearchFormat:=False, ReplaceFormat:=False)

答案 1 :(得分:0)

默认情况下,Excel将尝试继续替换整个字符串 需要只替换一些字符:

_xlsheetActive.Cells.Replace(What:=Chr(10), Replacement:="", LookAt:=2, SearchOrder:=1, MatchCase:=False, SearchFormat:=False, ReplaceFormat:=False)