VB.net/Excel-“向后”选项卡索引每个带有文本框的迭代

我有一个3个文本框和1个button的表单。

textbox1具有选项卡索引0,它的文本= 1

textbox2具有选项卡索引1,它的文本= 2

textbox3的标签索引2,它的文本= 3

我想迭代通过文本框,并将其值放入单元格,以便…

范围(“A1”)。value = txtbox1.text(即:A1 =“1”)range(“A2”).value = txtbox2.text(即:A2 =“2”)范围(“A3”)。 = txtbox3.text(即:A3 =“3”)

但是我得到的是…

范围(“A1”)。value = txtbox1.text(即:A1 =“3”)range(“A2”)。value = txtbox2.text(即:A2 =“2”)范围(“A3”)。 = txtbox3.text(即:A3 =“1”)

我试图反转文本框的标签索引,但它不会改变“向后迭代”。

有什么我可以做的改变这一点,使循环运行从最低的标签索引到最高?

谢谢!

公共class级表格1

Private Sub Button1_Click_1(ByVal发件人为System.Object,ByVal e为System.EventArgs)处理Button1.Click

Dim objExcel As New Microsoft.Office.Interop.Excel.Application 'Declaring the object. objExcel.Visible = True 'Setting Excel to visible. Dim cntrl As Control With objExcel .Workbooks.Add() 'Adding a workbook. .Range("A1").Select() 'Selecting cell A1. End With 'Form contains 3 text boxes, with one number in each (1,2,3), and one button to fire the code in this sub. For Each cntrl In Me.Controls 'For every control on the form... If TypeOf (cntrl) Is TextBox Then 'If the control is a textbox, then... With objExcel .ActiveCell.Value = cntrl.Text 'place the control's text in the active cell and... .ActiveCell.Offset(1, 0).Activate() 'offset down one row. End With End If 'If the control is not a textbox (if it's the button), do nothing. Next 'Go to the next control. objExcel = Nothing 'Release the object. GC.Collect() 'Clean up. 

End Sub End Class

听起来这可能是Excel对控件进行迭代的方式。 你有没有试过,看看输出是什么?

  Dim objExcel As New Microsoft.Office.Interop.Excel.Application 'Declaring the object. objExcel.Visible = True 'Setting Excel to visible. Dim cntrl As Control With objExcel .Workbooks.Add() 'Adding a workbook. .Range("A3").Select() 'Selecting cell A3. End With 'Form contains 3 text boxes, with one number in each (1,2,3), and one button to fire the code in this sub. For Each cntrl In Me.Controls 'For every control on the form... If TypeOf (cntrl) Is TextBox Then 'If the control is a textbox, then... With objExcel .ActiveCell.Value = cntrl.Text 'place the control's text in the active cell and... .ActiveCell.Offset(-1, 0).Activate() 'offset up one row. End With End If 'If the control is not a textbox (if it's the button), do nothing. Next 'Go to the next control. objExcel = Nothing 'Release the object. GC.Collect() 'Clean up. 

使用For Each循环意味着你不关心你在做什么顺序。

我会做的是使用控件的“标签”属性来保存你想要的答案在行号:

 For Each cntrl In Me.Controls If TypeOf (cntrl) Is TextBox Then objExcel.ActiveSheet.Cells(cntrl.Tag, 1).Value = cntrl.Text End If Next 

您也可以在仅包含关键文本框的表单上添加隐藏面板,然后使用传统的FOR循环而不是“For Each”:

 Dim i as integer Dim myBox as textBox For i = 1 to 3 set myBox = Me.Panel1.Controls(i) objExcel.ActiveSheet.Cells(myBox.Tag, 1).Value = myBox.Text Next i 

它应该按Tab键顺序。 你甚至可以跳过types检查,因为你已经知道它是什么。