Visual Studio 2015 - 操作Excel?

时间:2015-07-22 07:34:53

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

我有750个Excel文件,我想

  1. 通过删除带有星号标题的数据列进行清理,
  2. 然后将一些数据并将其放入新的工作簿工作表中,将其他数据放入同一工作簿工作表中,并将其他一些数据放入第二个新工作簿中。
  3. 我在Visual Studio 2015中创建了一个WPF项目,其中包含一个带有2个

    单选按钮的对话框
    1. 清理数据,
    2. 生成新文件。
    3. 这是我的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)工作表不是Application [第19行]的成员

      b)工作表不是申请[第20行]的成员

      c)&x; xlOpenXMLWorkbook&#39;没有宣布。由于其保护级别,它可能无法访问。

2 个答案:

答案 0 :(得分:1)

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

  

Application.Workbooks.Worksheets

对于c),最简单的出路:

  

从Excel(Alt + F11)进入VBE

     

按F2显示对象浏览器

     

寻找xlOpenXMLWorkbook

结果:Const xlOpenXMLWorkbook = 51 (&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

答案 1 :(得分:1)

要引用工作表,您可以使用ws = wb.Worksheets(1)ws = wb.Worksheets("Sheet1")ws = excelApp.ActiveWorkbook.Worksheets(1)并使用xlOpenXMLWorkbook同时使用相应枚举XlFileFormat的名称:XlFileFormat.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的示例)。 enter image description here