这个宏在空白活动单元格中添加数据但是我需要在最后一个空行中添加数据在给定宏中是正确的
Sub FillDateSenderFrom()
For i = 1 To 3
If Controls("TextBox" & i) <> "" Then
If i = 1 Then
Cells(Rows.Count, 4).End(xlUp).End(xlToLeft).Offset(0, i - 1).Select
Range(ActiveCell, ActiveCell.End(xlUp).Offset(1, 0)).Value = Controls("TextBox" & i).Text
Else
Cells(Rows.Count, 4).End(xlUp).End(xlToLeft).Offset(0, 1).Select
Range(ActiveCell, ActiveCell.End(xlUp).Offset(1, 0)).Value = Controls("TextBox" & i).Text
End If
End If
Next i
End Sub
答案 0 :(得分:0)
您需要定义最后一行,并避免使用Select
和ActiveCell
,Activate
- How to avoid using Select in Excel VBA。您的代码的一些小工作示例如下所示:
Private Sub CommandButton1_Click()
i = 1
Dim myRow As Long
If Controls("TextBox" & i) <> "" Then
myRow = lastRow(columnToCheck:=4)
Cells(myRow, 4) = Controls("TextBox" & i).Text
End If
End Sub
Function lastRow(Optional wsName As String, Optional columnToCheck As Long = 1) As Long
Dim ws As Worksheet
If wsName = vbNullString Then
Set ws = ActiveSheet
Else
Set ws = Worksheets(wsName)
End If
lastRow = ws.Cells(ws.Rows.Count, columnToCheck).End(xlUp).Row
End Function
一般情况下,如果您正在处理表单,最好提及它。