VB.Net - 循环槽行并在其单元格中输入数据



您好,我想为从 4 到 50 的每一行将一个值(从文本框中作为数字 (17))添加到单元格的第 4 列(从左到右), 另一个值(文本框作为数字(57))从 50 到最后一行,数据在"A"列中。 所以,我已经打开了 excel 文件,在代码中运行 excel 文件中的宏,我可以保存它,但只有我的第一行将 17 列中的值更改为 4。而且我实际上不需要更改第一行,我需要在单元格中从第二行输入数据到最后一行。有人可以帮我吗?

Private Sub ReportBtn_Click(sender As Object, e As EventArgs) Handles Report_Btn.Click
Dim oExcel As Excel.Application
Dim oBook As Excel.Workbook
Dim oBooks As Excel.Workbooks
Dim wsheet As Excel.Worksheet
If MORCheckbox.Checked Then
Dim nowYear As Integer = Date.Now.Year
Dim MontText As String = MonatTextBox.Text
Dim path As String = "C:TEST" & nowYear & "" & MontText & ""
Dim name As String = "Filename" & MontText & " " & nowYear & ".xlsx"    
Dim pathandname As String = (path & name)
If Not Directory.Exists(path) Then
Directory.CreateDirectory(path)
End If
oExcel = CreateObject("Excel.Application")
oExcel.Visible = False
oBooks = oExcel.Workbooks
oBook = oBooks.Open("C:TEST2Report - Test.xlsm")
oExcel.Run("TestMACRO")
Dim numrows As Integer
numrows = oBook.Sheets("Sheet1").UsedRange.Rows.Count
wsheet = oBook.Worksheets(1)
Dim range1 As Excel.Range = wsheet.Range("A1")
For Each cell1 As Excel.Range In range1.Cells
If numrows >= 2 Or numrows <= 50 Then
wsheet.Cells(4).value = "17"
ElseIf numrows >= 51 Then
wsheet.Cells(4).value = "57"
End If
Next
oExcel.DisplayAlerts = False
oBook.SaveAs(pathandname, 51) ' 51 == xlsx
oBook.Close()
oBook = Nothing
oExcel.Quit()
oExcel = Nothing
Else
End If

问题是只有第一行中的第 4 个单元格更改为 17,而其他行/单元格没有更改。

你的循环可能看起来更像这样。您需要某种方法来跟踪当前行,然后将其传递到Cells()方法中。我希望这对您有所帮助并让您走上正轨。

Dim currentRow As Long
For currentRow = 2 To numrows Step 1
If currentRow >= 2 Or currentRow <= 50 Then
wsheet.Cells(currentRow, 4).value = "17"
ElseIf currentRow >= 51 Then
wsheet.Cells(currentRow, 4).value = "57"
End If
Next

最新更新