在Excel中创建和读取表vb使用VB

时间:2016-05-25 15:20:24

标签: vb.net excel excel-2010

我在Visual Studio 2010中创建了Excel Workbook 2010项目。

enter image description here

我添加了一个功能区并在其上添加了一个按钮。

我想在单击按钮时从Excel文件中读取值。

Private Sub Button1_Click(sender As System.Object, e As
Microsoft.Office.Tools.Ribbon.RibbonControlEventArgs) Handles Button1.Click

还有可能在Excel表格的载入上创建一个表吗?

如果是,我想在点击按钮后阅读该表。

在Excel中创建表格,如果是好的做法请咨询。

Private Sub Feuil1_Startup() Handles Me.Startup

        With Me
            .ListObjects.Add(Excel.XlListObjectSourceType.xlSrcRange, .Range("$C$2:$T$7"), , Excel.XlYesNoGuess.xlYes).Name = "Table1"
            .Range("C2").Value = "ZRouteName"
            .Range("D2").Value = "MondayIndicator"

加载Excel表格表

Private Sub Feuil1_Startup() Handles Me.Startup
    ' Dim nr As Microsoft.Office.Tools.Excel.NamedRange = _
    'Me.Controls.AddNamedRange(Me.Range("A2"), "NamedRange1")
    'nr.Value2 = "This text was added by using code"
    With Me
        .ListObjects.Add(Excel.XlListObjectSourceType.xlSrcRange, .Range("$C$2:$T$7"), , Excel.XlYesNoGuess.xlYes).Name = "Table1"
        .Range("C2").Value = "ZRouteName"
        .Range("D2").Value = "MondayIndicator"
        .Range("E2").Value = "TuesdayIndicator"
        .Range("F2").Value = "WednesdayIndicator"
        .Range("G2").Value = "ThursdayIndicator"
        .Range("H2").Value = "FridayIndicator"
        .Range("I2").Value = "SaturdayIndicator"
        .Range("J2").Value = "SundayIndicator"
        .Range("K2").Value = "StartDate"
        .Range("L2").Value = "Zorganiser"
        .Range("M2").Value = "DayNumber"
        .Range("N2").Value = "ZEmployeeResponsible"
        .Range("O2").Value = "VisitDate"
        .Range("P2").Value = "StartTime"
        .Range("Q2").Value = "DriveTime"
        .Range("R2").Value = "PreparationTime"
        .Range("S2").Value = "Duration"
        .Range("T2").Value = "ZAccountID"
    End With
End Sub

现在我想从表1 OnClick事件按钮

中读取值
Private Sub Button1_Click(sender As System.Object, e As
Microsoft.Office.Tools.Ribbon.RibbonControlEventArgs) Handles Button1.Click

1 个答案:

答案 0 :(得分:1)

这是从功能区类访问工作表的示例。

Private Sub Button1_Click(sender As System.Object, e As Microsoft.Office.Tools.Ribbon.RibbonControlEventArgs) Handles Button1.Click
    MessageBox.Show(Globals.Feui11.Cells(1, 1).Value)
End Sub

或使用Range

Private Sub Button1_Click(sender As System.Object, e As Microsoft.Office.Tools.Ribbon.RibbonControlEventArgs) Handles Button1.Click
        MessageBox.Show(Globals.Feui11.Range("A1").Value)
End Sub

这个外部循环遍历UsedRange中的行,并且每行迭代遍历列。如果您知道需要为数据查找哪些列,则可能不需要列循环。

For row As Integer = 1 To Globals.Feui11.UsedRange.Rows.Count Step 1
            For column As Integer = 1 To Globals.Feui11.UsedRange.Columns.Count Step 1
                'Do stuff with this
                'Globals.Feui11.Cells(row, colunm).Value
            Next
        Next