您好,我想为2到50的每一行在第4列(从左到右)的单元格中添加一个值(从文本框中作为数字(17)), 另一个值(文本框为number(57))从50到“ A”列中包含数据的最后一行。 因此,我已经在代码中打开了excel文件,在excel文件中运行了宏,可以保存它,但是仅第一行将第4栏中的值更改为17。而且我实际上不需要更改第一行,我需要在单元格中从第二行到最后一行输入数据。有人可以帮我吗?
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:\TEST2\Report - 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,而其他行/单元格未更改。
答案 0 :(得分:0)
您的循环应该看起来像这样。您需要某种方式来跟踪当前行,然后将其传递到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