0

我在一个表单上有两个文本框;一个保存单词,另一个保存其数值,该数值是根据用户键入的内容计算得出的。我有一个分隔每个句子并在 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
4

2 回答 2

1

编辑:我对此代码进行了重大更改并对其进行了测试;它应该做你正在寻找的东西

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
于 2013-07-09T02:45:20.053 回答
0

尝试使用

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
于 2013-07-08T07:44:56.573 回答