![](/img/trans.png)
[英]in excel, running from vb.net, can I add the values of all the cells in one sheet to the cells in a different sheet?
[英]Display the textboxes results in Excel sheet cells in vb.net
我在表单上有两个文本框。 一个保存单词,另一个保存其数值,该数值是根据用户键入的内容计算出来的。 我有一个子句,用于分隔每个句子并在Excel中显示每个句子的总数。 这是从下面列出的vb.net代码生成的输出。 所有单词都在A列中,所有值都在B列中。 如何修改代码,以便将每个句子及其值插入两列? 在到达字符串“总计为句子1”之后。 它应该开始在C&D列等中插入单词及其值。 句子一及其值应显示在A和B列中,句子二及其值应显示在C和D列中,依此类推。 请参阅所附图片。 红色文字是我当前拥有的内容,下面是您想要的结果。 谢谢!
我在vb.net中的代码是:
Private Sub Export_Click(sender As System.Object, e As System.EventArgs) Handles btnCreate.Click
xlWorkBook = xlApp.Workbooks.Add
xlApp.Visible = True
xlWorkSheet = xlWorkBook.Sheets("Sheet1")
Dim columnANum As Integer
Dim columnBNum
columnBNum = 2
columnANum = 2
With xlWorkSheet
.Range("A1").Value = "Word"
For Each cellA As String In txtWord.Text.Split(vbLf)
.Range("A" & columnANum.ToString).Value = cellA
columnANum += 1
Next
.Range("B1").Value = "Value"
For Each cellB As String In txtValue.Text.Split(vbLf)
.Range("B" & columnBNum.ToString).Value = Convert.ToInt32(cellB)
columnBNum += 1
Next
End With
End Sub
编辑:我对该代码进行了重大更改,并对其进行了测试; 它应该做你想要的
Sub testExcelColumns()
Dim xlApp As Object = CreateObject("Excel.Application")
Dim xlWorkBook As Object
Dim xlWorkSheet As Object
xlWorkBook = xlApp.Workbooks.Add
xlApp.Visible = True
xlWorkSheet = xlWorkBook.Sheets("Sheet1")
Dim RowNum As Integer = 1
Dim ColNum As Integer = 1
'use .cells(row, column) instead of .range
xlWorkSheet.cells(RowNum, ColNum).Value = "Word"
For Each cellA As String In txtWord.Text.Split(vbLf)
'increment the row
RowNum += 1
'set the value
xlWorkSheet.cells(RowNum, ColNum).value = cellA
If cellA.StartsWith("Total") Then
ColNum += 2
RowNum = 1
xlWorkSheet.cells(RowNum, ColNum).Value = "Word"
End If
Next
'increment to the second column and first row
ColNum = 2
RowNum = 1
'set title
xlWorkSheet.cells(RowNum, ColNum).Value = "Value"
For Each cellB As String In txtValue.Text.Split(vbLf)
'increment the row
RowNum += 1
'set the value
xlWorkSheet.cells(RowNum, ColNum).value = cellB
'get value of cell to the left
Dim t As String = xlWorkSheet.cells(RowNum, ColNum).offset(0, -1).value
If Not t Is Nothing AndAlso t.StartsWith("Total") Then
ColNum += 2
RowNum = 1
xlWorkSheet.cells(RowNum, ColNum).Value = "Value"
End If
Next
End Sub
尝试使用
Dim RowNum as Integer = 1
Dim ColNum as Integer = 1
使用.cells而不是.range
xlWorkSheet.Cells(RowNum, ColNum).value = "Word"
xlWorkSheet.Cells(RowNum, ColNum).value = "Value"
根据需要更新行和列
RowNum += 1
ColNum += 1
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.