2

此代码将文本文件作为输入并将每一行存储在字符串数组中,循环遍历每一行并检查条件并最终填充数组。

当我尝试通过.rangeexcel 对象库的方法将此一维数组传输到 excel 列时,它会用数组的第一个值(即数组(0))填充范围的所有单元格。

 sr = openFileDialog1.FileName()
            If (sr IsNot Nothing) Then

            Dim alltextlines() As String = IO.File.ReadAllLines(sr)
            Dim name As String
            Dim isvalid As Boolean
            Dim tempstr() As String
            Dim count As Integer = 0


            For Each myLine In alltextlines
                ReDim Preserve tempstr(count)
                If myLine.Contains(">") And myLine.Contains(" sds dsd") Then

                    isvalid = Integer.TryParse((Microsoft.VisualBasic.Mid(Microsoft.VisualBasic.LTrim(myLine), 3, 1)), 0)

                    If isvalid Then

                        name = Microsoft.VisualBasic.Left(Microsoft.VisualBasic.LTrim(myLine), 5)

                    Else
                        name = Microsoft.VisualBasic.Left(Microsoft.VisualBasic.LTrim(myLine), 7)

                    End If

                    tempstr(count) = name
                    count = count + 1
                End If

            Next
            Dim message As String = String.Join("..", tempstr)
            MsgBox(message)

            Dim oExcel As Object
            Dim oBook As Object
            Dim oSheet As Object

            'Start a new workbook in Excel.
            oExcel = CreateObject("Excel.Application")
            oBook = oExcel.Workbooks.Add
            oSheet = oBook.Worksheets(1)
            oSheet.Range("A1").Value = "SiteNames"
            oSheet.Range("A1:B1").Font.Bold = True
            oSheet.Range("A2").Resize(tempstr.Length).Value = tempstr




            oSheet = Nothing
            oBook = Nothing
            oExcel.Quit()
            oExcel = Nothing
            GC.Collect()


        Else
            MsgBox("TEXT FILE IS EMPTY", MsgBoxStyle.Critical, "Error")
        End If
    End If
End Sub
4

1 回答 1

2

您应该传递一个二维数组来设置范围值。这会使您的循环复杂化以仅提取符合预定义条件的行,并且您被迫进入第二个循环以填充二维数组

举个例子

Dim values(5) as string
values(0) = "Test0"
values(1) = "Test1"
values(2) = "Test2"
values(3) = "Test3"
values(4) = "Test4"

Dim tempstr(,) As String = new String(values.Length,1) {}
for x as Integer = 0 to values.Length - 1
    tempstr(x, 0) = values(x)
next


Dim oExcel as Object = CreateObject("Excel.Application")    
Dim oBook as Object = oExcel.Workbooks.Add 
Dim oSheet as Object = oBook.Worksheets(1) 
oSheet.Range("A1").Value = "SiteNames" 
oSheet.Range("A1").Font.Bold = True 
Dim r As Range = oSheet.Range("A2").Resize(tempStr.GetLength(0))
r.Value2 =  tempstr
oExcel.Visible = true
于 2012-09-22T17:09:40.590 回答