[英]Move right to next cell in Excel using vb.net
I need to name my headers according to the items I have in a combo box. 我需要根据组合框中的项目命名标题。 I'm basically taking the items from a combo box and adding them to the end of an existing header row in a excel sheet, so starting at the first empty cell in the headers row.
我基本上是从组合框中获取项目,并将其添加到excel工作表中现有标题行的末尾,因此从标题行中的第一个空单元格开始。 However, I can't seem to move to the next cell to the right which would be the next header/column name.
但是,我似乎无法移动到右侧的下一个单元格,即下一个标题/列名称。 Here is my code thus far:
到目前为止,这是我的代码:
For i = 0 To ComboBox1.Items.Count - 1
Dim s As String
s = Convert.ToString(ComboBox1.Items(i))
xlWorkSheet.Range(columnName & "1").Value = s
Next i
ColumnName is the next blank header in that row, Column "L", so from there i would like to populate that cell then move to the right to the next cell. ColumnName是该行中的下一个空白标题,即“ L”列,因此我要从那里填充该单元格,然后向右移动到下一个单元格。
As others have suggested, you can use Cells()
to help iterate easier. 正如其他人所建议的那样,您可以使用
Cells()
来简化迭代。 Note that the user/macro needs the column number , not letter : 请注意,用户/宏需要列号 ,而不是字母 :
Edit: How's this instead: 编辑:这是怎么回事:
Dim s As String
Dim myCol As Long
For i = 0 To ComboBox1.Items.Count - 1
myCol = Range(columnName & 1).Column
s = Convert.ToString(ComboBox1.Items(i))
xlWorksheet.Cells(1, myCol + i).Value = s
Next i
Loops are so yesterday :] 昨天的循环是如此:]
You can set all headers at once with something like: 您可以使用以下命令一次设置所有标题:
Dim headers = ComboBox1.Items.Cast(Of Object).ToArray
xlWorkSheet.Range("A1").Resize(1, headers.Length).Value2 = headers
Also, when you get acceptable answer you should check the green check next to it https://stackoverflow.com/tour 另外,当您获得可接受的答案时,您应该选中它旁边的绿色对勾https://stackoverflow.com/tour
if headers are not in row 1 so add another parameter of row and replace xlWorksheet.Cells(1, counter)
with 如果标题不在第1行中,则添加该行的另一个参数,并将
xlWorksheet.Cells(1, counter)
替换为
xlWorksheet.Cells(yourNewParameter, counter)
. xlWorksheet.Cells(yourNewParameter, counter)
。
use short
or integer
data type not Long
. 使用
short
或integer
数据类型,而不是Long
。
you dont need to create a variable for xlWorksheet.Cells(1, counter)
make your code shorter. 您不需要为
xlWorksheet.Cells(1, counter)
创建一个变量,以使您的代码更短。
code: 码:
Private Sub AddHeaders(ByVal columnNumberToStart As Short)
Dim counter As Short = columnNumberToStart
For i = 0 To ComboBox1.Items.Count - 1
xlWorksheet.Cells(1, counter) = ComboBox1.Items(i).ToString()
counter += 1
Next
End Sub
This is what finally worked for me 这终于对我有用
Dim headers = ComboBox1.Items.Cast(Of Object).ToArray
xlWorkSheet.Range(columnName & "1").Resize(1, headers.Length).Value2 = headers
This also worked: 这也起作用:
For i = 0 To ComboBox1.Items.Count - 1
Dim s As String
myCol = xlWorkSheet.Range(columnName & 1).Column
s = Convert.ToString(ComboBox1.Items(i))
xlWorkSheet.Cells(1, myCol + i).Value = s
Next i
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.