我正在编写代码,将项目成本插入到工作表中。我不是Excel专家,所以我使用本教程来指导我:https://www.youtube.com/watch?v=NO10WZ2prDQ (它是葡萄牙语,但您可以在视频的第一分钟内看到UserForm的功能)。
我想要做的是在工作表中插入成本,然后过滤它们,生成所有项目成本及其类别的报告。
这是我的UserForm:https://i.stack.imgur.com/pIzwT.png
在为Insert Button ('Inserir Custo')编写代码时,我输入了以下内容:
Dim iRow As Long
Dim ws As Worksheet
Set ws = Worksheets("Plan4")
iRow = ws.Cells.Find(What:="*", SearchOrder:=xlRows, SearchDirection:=xlPrevious, LookIn:=xlValues).Row + 1
ws.Cells(iRow, 1).Value = Me.ListBox1.Value
ws.Cells(iRow, 2).Value = Me.TextBox1.Value
Me.ListBox1.Value = ""
Me.TextBox1.Value = ""
Me.TextBox1.SetFocusExcel在代码的iRow行上显示了一个错误,但我不知道哪里出了问题。单击该按钮时,我希望代码在单元格中插入ListBox1的结果,在旁边的另一个单元格中插入TextBox1的结果。
有人能帮我吗?我写错什么了?
谢谢!
发布于 2017-09-06 20:26:57
Private Sub CommandButton1_Click()
Dim iRow As Long
Dim ws As Worksheet
Dim FoundIt As Range
Set ws = Worksheets("Plan4")
Set FoundIt = ws.Cells.Find(What:="*", SearchOrder:=xlRows, SearchDirection:=xlPrevious, LookIn:=xlValues)
If FoundIt Is Nothing Then
MsgBox ("nothing found")
Else
iRow = FoundIt.Row + 1
ws.Cells(iRow, 1).Value = Me.ListBox1.Value
ws.Cells(iRow, 2).Value = Me.TextBox1.Value
Me.ListBox1.Value = ""
Me.TextBox1.Value = ""
Me.TextBox1.SetFocus
End If
End Sub问题是,如果find函数没有得到匹配,它将返回nothing值,然后尝试从空中获取行号。上面的代码稍微简化了一些,只有在行号是有效范围的情况下,才会尝试获取行号。
发布于 2017-09-06 20:45:10
您需要在A1开始搜索,因为您正在从那里向上搜索,向上滚动到工作表底部,并一直向上滚动,直到它到达数据为止。
iRow = ws.Cells.Find(What:="*", after:=ws.range("A1"), SearchOrder:=xlRows, SearchDirection:=xlPrevious, LookIn:=xlValues).Row + 1发布于 2017-09-07 06:21:42
Dim rw As Range, f As Range
Dim ws As Worksheet
Set ws = Worksheets("Plan4")
Set f = ws.Cells.Find(What:="*", SearchOrder:=xlRows, _
SearchDirection:=xlPrevious, LookIn:=xlValues)
If Not f Is Nothing Then
Set rw = f.Offset(1,0).EntireRow
Else
Set rw = ws.Rows(1)
End If
With rw
.Cells(1).Value = Me.ListBox1.Value
.Cells(2).Value = Me.TextBox1.Value
End With
Me.ListBox1.Value = ""
Me.TextBox1.Value = ""
Me.TextBox1.SetFocushttps://stackoverflow.com/questions/46083221
复制相似问题