【问题标题】:Visual Studio 2015 - Manipulating Excel?Visual Studio 2015 - 操作 Excel?
【发布时间】:2015-07-22 07:34:53
【问题描述】:

我有 750 个 Excel 文件想要处理

  1. 通过删除标题带有星号的数据列进行清理,
  2. 然后获取其中一些数据并将其放入新的工作簿工作表中,将其他数据放入同一个工作簿工作表中,并将其他一些数据放入第二个新工作簿中。

我在 Visual Studio 2015 中创建了一个 WPF 项目,其中包含一个带有 2 个单选按钮的小对话框

  1. 干净的数据,
  2. 生成新文件。

这是我的 VB 代码:

    Class MainWindow
    Dim wb As Microsoft.Office.Interop.Excel._Workbook
    Dim ws As Microsoft.Office.Interop.Excel._Worksheet
    Dim iCol As Integer
    Dim strName As String
    Dim iIndex As Integer
    Dim strPath As String
    Dim strFile As String

    Private Sub button_Click(sender As Object, e As RoutedEventArgs) Handles button.Click
        If cleanRadioButton.IsChecked = True Then
            strPath = "c:\test\old\"
            strFile = Dir(strPath & "*.csv")
            Do While strFile <> ""

                wb = wb.Open(Filename:=strPath & strFile)

                'Loop through the sheets.
                For iIndex = 1 To Application.Worksheets.Count
                    ws = Application.Worksheets(iIndex)

                    'Loop through the columns.
                    For iCol = 1 To ws.UsedRange.Columns.Count
                        'Check row 1 of this column for the char of *
                        If InStr(ws.Cells(10, iCol).Value, "*") > 0 Then
                            'We have found a column with the char of *
                            ws.Columns(iCol).EntireColumn.Delete
                            ws.Columns(iCol + 1).EntireColumn.Delete
                            ws.Columns(iCol + 2).EntireColumn.Delete
                        End If
                    Next iCol

                Next iIndex
                wb.SaveAs(Filename:="C:\test\new\" & wb.Name, FileFormat:=xlOpenXMLWorkbook)
                wb.Close(SaveChanges:=False)
                strFile = Dir()
            Loop
            MessageBox.Show("The csv files have now been cleaned.  Congrats.")
        Else inputRadioButton.IsChecked = True
            MessageBox.Show("The data has now been split into Trajectory and ForcePlate input files.  High 5.")
        End If
    End Sub
End Class

我遇到 3 个错误,但不知道如何解决它们

a) Worksheets 不是 Application [第 19 行] 的成员

b) Worksheets 不是 Application [line 20] 的成员

c) 'xlOpenXMLWorkbook' 未声明。由于其保护级别,它可能无法访问。

【问题讨论】:

  • 我同时使用 VB.Net 和 VBA。 VB.Net 具有丰富的功能,包括访问保存在任何版本的 Excel 下的工作簿,生成的可执行文件可以比 VBA 宏快一百倍。我认为 VB.Net 是更好的语言,我使用它比 VBA 更多。但是,从 VB.Net 访问工作簿很慢。如果程序的唯一目标是操作工作簿,我会使用 VBA。

标签: vb.net excel visual-studio-2015


【解决方案1】:

对于 a) 和 b),模式是:

Application.Workbooks.Worksheets

对于 c),最简单的方法:

从 Excel 进入 VBE (Alt + F11)

按 F2 显示对象浏览器

寻找 xlOpenXMLWorkbook

结果:Const xlOpenXMLWorkbook = 51 (&amp;H33) 因此,只需将其替换为值 51!


这是您修改后的代码:

  Class MainWindow
    Dim wb As Microsoft.Office.Interop.Excel._Workbook
    Dim ws As Microsoft.Office.Interop.Excel._Worksheet
    Dim iCol As Integer
    Dim strName As String
    Dim iIndex As Integer
    Dim wbIndex As Integer
    Dim strPath As String
    Dim strFile As String

    Private Sub button_Click(sender As Object, e As RoutedEventArgs) Handles button.Click
        If cleanRadioButton.IsChecked = True Then
            strPath = "c:\test\old\"
            strFile = Dir(strPath & "*.csv")
            Do While strFile <> ""

                wb = wb.Open(Filename:=strPath & strFile)

                'Loop through the sheets.
                For wbIndex = 1 To Application.Workbooks.Count
                    For iIndex = 1 To Application.Workbooks(wbIndex).Worksheets.Count
                        Ws = Application.Workbooks(wbIndex).Worksheets(iIndex)
    
                        'Loop through the columns.
                        For iCol = 1 To Ws.UsedRange.Columns.Count
                            'Check row 1 of this column for the char of *
                            If InStr(Ws.Cells(10, iCol).Value, "*") > 0 Then
                                'We have found a column with the char of *
                                Ws.Columns(iCol).EntireColumn.Delete
                                Ws.Columns(iCol + 1).EntireColumn.Delete
                                Ws.Columns(iCol + 2).EntireColumn.Delete
                            End If
                        Next iCol
    
                    Next iIndex
                Next wbIndex
                'Const xlOpenXMLWorkbook = 51 (&H33)
                wb.SaveAs(Filename:="C:\test\new\" & wb.Name, FileFormat:=51)
                wb.Close(SaveChanges:=False)
                strFile = Dir()
            Loop
            MessageBox.Show ("The csv files have now been cleaned.  Congrats.")
        Else: inputRadioButton.IsChecked = True
            MessageBox.Show ("The data has now been split into Trajectory and ForcePlate input files.  High 5.")
        End If
    End Sub
End Class

【讨论】:

  • 嗨 R3UK - 感谢您不厌其烦地回复。我实施了您修改后的代码,但尽管这解决了问题 c) [thx btw],错误 a) 和 b) 仍然存在以下形式:ActiveWorkbook is not a member of Application....有什么想法吗?谢谢
  • @TomChambers :所以ActiveWorkbook 可能不在Visual Studio 中,所以我在Workbooks 上添加了一个循环以避免使用它,唯一的问题是这可能会扫描所有打开的工作簿,如果您愿意,可以添加对名称或其他内容的测试!
【解决方案2】:

要引用工作表,您可以使用ws = wb.Worksheets(1)ws = wb.Worksheets("Sheet1")ws = excelApp.ActiveWorkbook.Worksheets(1),要使用xlOpenXMLWorkbook,也可以使用相应枚举的名称XlFileFormatXlFileFormat.xlOpenXMLWorkbook

此简化示例打开工作簿 Test.xlsx,在单元格 A1 中写入文本并将其保存到新文件夹。

Imports System.IO
Imports Microsoft.Office.Interop.Excel

Public Class MainWindow

    Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
        Dim excelApp As Application
        Dim wb As _Workbook
        Dim ws As _Worksheet
        Dim rng As Range
        Dim strPathOld = "c:\temp\old"
        Dim strPathNew = "c:\temp\new"

        ' get excel application reference
        excelApp = New Application
        excelApp.Visible = True
        excelApp.ScreenUpdating = True

        ' open the workbook
        wb = excelApp.Workbooks.Open(Path.Combine(strPathOld, "Test.xlsx"))

        ' set reference to the sheet with index 1
        ws = wb.Worksheets(1)

        ' or use sheet name
        ' ws = wb.Worksheets("Sheet1")

        ' or use ActiveWorkbook if it exists
        ' ws = excelApp.ActiveWorkbook.Worksheets(1)

        ' write text in cell A1
        rng = ws.Range("A1")
        rng.Formula = "Test123"

        ' save the workbook in new location
        wb.SaveAs(Filename:=Path.Combine(strPathNew, wb.Name), _
              FileFormat:=XlFileFormat.xlOpenXMLWorkbook)

        excelApp.Quit()

    End Sub
End Class

注意:为您的 Excel 版本添加对 MS Office Interop 的引用(此处以 Excel 2007 为例)。

【讨论】:

  • 您好,感谢您抽出宝贵时间回复。我输入了您的代码,但我不断收到错误消息,即应用程序中未定义或未包含事物...有什么想法吗??
  • @Tom 我不知道问题出在哪里。但是看到编辑的答案,在我的示例项目中添加了一张 Excel-Interop dll 参考的图片。 HTH
  • 可能您代码中的应用程序类型不是 Excel-Application?尝试使用完全限定名,写Microsoft.Office.Interop.Excel.Application
  • @TomCh 不客气,我很高兴它有帮助!如果你喜欢这个答案,你可以接受它。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-10-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多