我被困在这里,我想将5个文本框中的数据插入到列中的现有excel文件中。我找到了代码但是按行插入。我有一个代码,找到最后一个非空行,从那一行我想移动到下一行并在那里插入数据,例如最后一行是A2,我想将新数据插入A3,B3,C3,D3 ,E3。
我无法为此获得正确的循环。
Dim lRow As Long = 0
Call OpenExcelFile("C:\Users\PB\Desktop\BookRecords.xlsx", 1)
With xlWorkSheet
If EXL.WorksheetFunction.CountA(.Cells) <> 0 Then
lRow = .Cells.Find(What:="*", _
After:=.Range("A2"), _
LookAt:=Excel.XlLookAt.xlPart, _
LookIn:=Excel.XlFindLookIn.xlFormulas, _
SearchOrder:=Excel.XlSearchOrder.xlByRows, _
SearchDirection:=Excel.XlSearchDirection.xlPrevious, _
MatchCase:=False).Row
Else
lRow = 1
End If
lRow += 1
End With
MessageBox.Show("The last row in Sheet1 which has data is " & lRow)
Dim j As Integer
j = 3
For i As Integer = j To 8
xlWorkSheet.Range(xlWorkSheet.Cells(lRow + 1, j).item).Value = txtTitle.Text
xlWorkSheet.Range(xlWorkSheet.Cells(lRow + 1, j).item).Value = txtAuthor.Text
xlWorkSheet.Range(xlWorkSheet.Cells(lRow + 1, j).item).Value = txtEdition.Text
xlWorkSheet.Range(xlWorkSheet.Cells(lRow + 1, j).item).Value = txtPublisher.Text
xlWorkSheet.Range(xlWorkSheet.Cells(lRow + 1, j).item).Value = txtISBN.Text
Next
j += 1
Call SaveAndCloseExcelSub()
答案 0 :(得分:2)
这有用吗:
Dim j As Integer
j = 3
For i As Integer = j To 8
MsgBox("Cell column: " & ColumnNumberToName(i))
Next
将数字转换为Excel列名称的代码(A-Z,AA等):
Public Shared Function ColumnNumberToName(columnNumber As Int32) As String
Dim dividend As Int32 = columnNumber
Dim columnName As [String] = [String].Empty
Dim modulo As Int32
While dividend > 0
modulo = (dividend - 1) Mod 26
columnName = Convert.ToChar(65 + modulo).ToString() + columnName
dividend = DirectCast(((dividend - modulo) / 26), Int32)
End While
Return columnName
End Function
Public Shared Function ColumnNameToNumber(columnName As [String]) As Int32
If [String].IsNullOrEmpty(columnName) Then
Throw New ArgumentNullException("columnName")
End If
Dim characters As Char() = columnName.ToUpperInvariant().ToCharArray()
Dim sum As Int32 = 0
Dim i As Int32 = 0
While i < characters.Length
sum *= 26
sum += (characters(i) - "A"C + 1)
System.Math.Max(System.Threading.Interlocked.Increment(i),i - 1)
End While
Return sum
End Function
答案 1 :(得分:2)
实际上,你所有的值都被写入同一个单元格;然后你向下移动一行再做一次。单元格被称为(行,列) - 因此您需要像这样更改代码:
Dim j As Integer
j = 3
For i As Integer = j To 8
xlWorkSheet.Cells(lRow + i, 1).Value = txtTitle.Text
xlWorkSheet.Cells(lRow + i, 2).Value = txtAuthor.Text
xlWorkSheet.Cells(lRow + i, 3).Value = txtEdition.Text
xlWorkSheet.Cells(lRow + i, 4).Value = txtPublisher.Text
xlWorkSheet.Cells(lRow + i, 5).Value = txtISBN.Text
Next
如果您向i = 3
添加lRow
,则不确定是否需要dim i as Integer
i = 1; ' if you want column A
With xlWorkSheet
.Cells(lRow , i).Value = txtTitle.Text
.Cells(lRow + 1, i).Value = txtAuthor.Text
.Cells(lRow + 2, i).Value = txtEdition.Text
.Cells(lRow + 3, i).value = txtPublisher.Text
.Cells(lRow + 4, i).Value = txtISBN.Text
End With
,但我相信您可以解决这个问题。
如果您想要逆转订单,请执行此操作(此示例仅复制一批文本...我开始怀疑不需要循环)
{{1}}