我想在Form2中使用我在Form1中声明的变量

时间:2016-12-26 14:36:14

标签: vb.net forms variables

这是我的表格1

Public Class Form1
Dim excelapp As Microsoft.Office.Interop.Excel.Application
Dim excelwb As Microsoft.Office.Interop.Excel.Workbook
Dim excelws As Microsoft.Office.Interop.Excel.Worksheet

Public Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
    'Calling form for New
    Dim new1 As New Form2
    new1.Show()
End Sub

Private Sub Button3_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button3.Click
    'To Open File
    Using FileDialog As New OpenFileDialog
        FileDialog.Title = "Select your Excel file"
        FileDialog.Filter = "Microsoft Excel|*.xl*|All Files|*.*"
        FileDialog.ShowDialog()
        Process.Start(FileDialog.FileName)
        Dim s As String = FileDialog.FileName
        excelwb = excelapp.Workbooks.Open(FileDialog.FileName)
        excelws = excelwb.Worksheets(1)


        'End Using

        ' Using FileProcess As Process = Process.Start(FileDialog.FileName)

    End Using

    'Calling form for Open

    Dim new1 As New Form2
    new1.Show()

这是我的表格2

       Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click
    'New Entry in existing excel file
    excelws.Cells(3, 1).Value = TextBox1.Text
    excelws.Cells(3, 2).Value = TextBox2.Text
    excelws.Save()
End Sub

我想在form2中使用form1中的所有变量和所有内容。 请帮我如何在我的表格2中使用这些东西。 我准备一个应用程序来获取用户输入并为其生成pdf。 即时通讯使用Excel保存数据,使用VB Express 2010创建表单。 请指导我:)非常感谢。

1 个答案:

答案 0 :(得分:1)

将表单1中的excelws等声明更改为Public

Public excelapp As Microsoft.Office.Interop.Excel.Application
Public excelwb As Microsoft.Office.Interop.Excel.Workbook
Public excelws As Microsoft.Office.Interop.Excel.Worksheet

然后,假设您的Form1仍然被称为UserForm1,您可以按如下方式更改您的Form 2代码:

Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click
    'New Entry in existing excel file
    UserForm1.excelws.Cells(3, 1).Value = TextBox1.Text
    UserForm1.excelws.Cells(3, 2).Value = TextBox2.Text
    UserForm1.excelws.Save()
End Sub

如果没有调用UserForm1,只需替换相应的名称。