VBA 函数调用不正确
Posted
技术标签:
【中文标题】VBA 函数调用不正确【英文标题】:VBA function not calling correctly 【发布时间】:2018-02-21 12:58:54 【问题描述】:我有以下函数,它找到工作表中的最后一行,并试图在我的 Sub Submit_data() 中调用它。子似乎无法识别它,因此消息框返回 0。但是,如果我将完全相同的代码放在测试子中而没有其他任何内容,它就可以工作。有人知道为什么会这样吗?注意:我的提交数据子较长,所以我只包含了发生错误的第一部分。
Private Function lasrow() As Long
Worksheets("Data - Complete").Select
lasrow = Cells.Find(What:="*", _
After:=Range("A1"), _
LookAt:=xlPart, _
LookIn:=xlFormulas, _
SearchOrder:=xlByRows, _
SearchDirection:=xlPrevious, _
MatchCase:=False).Row
End Function
Sub Submit_data()
Dim lRow As Long
Dim lCol As Long
Dim colName As Long
Dim resetrange As Range
Dim indicator As String
Dim Dire(1 To 6, 1 To 2) As String
Dim i As Integer
Dim lasrow As Long, lasCol As Long
Dim lro As Long
Dire(1, 1) = "B2": Dire(1, 2) = "D2"
Dire(2, 1) = "B3": Dire(2, 2) = "D3"
Dire(3, 1) = "B4": Dire(3, 2) = "D4"
Dire(4, 1) = "G7": Dire(4, 2) = "I7"
Dire(5, 1) = "G11": Dire(5, 2) = "I11"
Dire(6, 1) = "G13": Dire(6, 2) = "I13"
Application.ScreenUpdating = False
If IsEmpty(Range("I15")) = False Then
lro = lasrow
Worksheets("User").Select
Range("I15").Select
Application.CutCopyMode = False
Selection.Copy
Sheets("Data - Complete").Select
Cells(lro + 1, 5).Select 'problem with selecting column
ActiveSheet.Paste
Worksheets("User").Select
Range("I15").Select
Selection.ClearContents
MsgBox ("lRow is " & lro)
End If
【问题讨论】:
lro = lasrow
和 MsgBox ("lRow is " & lRow)
?错别字?使用选项显式。
错误在哪一行,错误到底是什么?
您正在声明一个与您的函数同名的变量。删除Dim lasrow As Long
。
啊,我会用这个代替谢谢!谢谢你们,SJR,你是对的,删除 Dim lasrow As Long 让它起作用了!
仅供参考,如果您在用户名前使用@
,则会向该用户发送警报。
【参考方案1】:
总结一下:
要解决您遇到的问题,您需要删除与您的函数同名的变量声明。
为了让它更简单,你可以删除这个函数,让你的 sub 像这样:
Sub Submit_data()
Dim lRow As Long
Dim lCol As Long
Dim colName As Long
Dim resetrange As Range
Dim indicator As String
Dim Dire(1 To 6, 1 To 2) As String
Dim i As Integer
Dim lasCol As Long
Dim lro As Long
Dire(1, 1) = "B2": Dire(1, 2) = "D2"
Dire(2, 1) = "B3": Dire(2, 2) = "D3"
Dire(3, 1) = "B4": Dire(3, 2) = "D4"
Dire(4, 1) = "G7": Dire(4, 2) = "I7"
Dire(5, 1) = "G11": Dire(5, 2) = "I11"
Dire(6, 1) = "G13": Dire(6, 2) = "I13"
Application.ScreenUpdating = False
If IsEmpty(Range("I15")) = False Then
'Change this so find the last row without the function
'The "1" is telling it to look in column "A"
'The ActiveSheet.Rows.Count is using the maximum number of possible rows as the row which is 1048576
'So it is starting in A1048576 and going up till it finds the first non-empty row and returning that row number
lro = ActiveSheet.Cells(ActiveSheet.Rows.count, 1).End(xlUp).row
Worksheets("User").Select
Range("I15").Select
Application.CutCopyMode = False
Selection.Copy
Sheets("Data - Complete").Select
Cells(lro + 1, 5).Select 'problem with selecting column
ActiveSheet.Paste
Worksheets("User").Select
Range("I15").Select
Selection.ClearContents
MsgBox ("lRow is " & lro)
End If
而且您仍然不需要 lasrow 变量以及此处显示的内容。
【讨论】:
以上是关于VBA 函数调用不正确的主要内容,如果未能解决你的问题,请参考以下文章
如何在 VBA 的另一个函数中调用我在 VBA 中创建的函数?