我正在尝试编写代码以在工作表上插入项目成本。我不是Excel专家,因此我使用本教程指导我: https://www.youtube.com/watch?v=NO10WZ2prDQ(用葡萄牙语,但你可以看到用户视频在视频的第一分钟内做了什么)
我想要做的是在工作表中插入成本,然后过滤它们以生成所有项目成本及其类别的报告。
这是我的UserForm: https://i.stack.imgur.com/pIzwT.png
编码插入按钮('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.SetFocus
Excel在代码的iRow行显示错误,但我不知道什么是错的。单击该按钮时,我希望代码在单元格中插入ListBox1的结果,并在其旁边的另一个单元格中插入TextBox1。
有人能帮助我吗?我写错了什么?
谢谢!
答案 0 :(得分:1)
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函数没有得到匹配它返回一个没有值,然后你尝试从没有得到行号。我上面的代码简化了一点,只是尝试获取行号如果它是有效范围。
答案 1 :(得分:0)
你需要在A1处开始搜索,因为你正在从那里向上搜索,它会翻到工作表底部并继续向上直到它到达数据
iRow = ws.Cells.Find(What:="*", after:=ws.range("A1"), SearchOrder:=xlRows, SearchDirection:=xlPrevious, LookIn:=xlValues).Row + 1
答案 2 :(得分:0)
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.SetFocus