如何解决VBA中的函数运行时错误

时间:2019-07-10 19:46:20

标签: excel vba function

从SubRoutine调用函数时,出现运行时错误。高亮显示的行是Do Until IsEmpty(.Cells(x, c))

生成的错误是RunTime Error 1004 Application - defined or object - defined error

代码

Private LastRow As Long
Private wb As Workbook: Set wb = ThisWorkbook
Private ws As Worksheet: Set ws = wb.Sheets("clientmenu")
Private CellRow As Integer    ' create a variable to hold the cell row
LastRow = Sheet3.Range("a" & Rows.count).End(xlUp).Row + 1
CellRow = ActiveCell.Row

Private x As Long, c As Long, s As Long
Const CONTACT_START As Long = 13 ' Column E
Const COL_PER_CONTACT As Long = 2 ' Columns per Contact
Const CONTACT_DROPS As Long = 14 'Column G
Const COL_PER_DROPS As Long = 2 'Columns per Contact


s = CONTACT_START
c = CONTACT_START
x = Me.lblRow
Z = LastRow

Public Function callDate() As Date
With ThisWorkbook.Sheets("clientmenu")
        ' Look for first empty one
        Do Until IsEmpty(.Cells(x, c))
            c = c + COL_PER_CONTACT
        Loop
        .Cells(x, c) = addnewClient.contact.value
        '.Cells(x, c + 1) = Me.cdates1.Value
    End With
End Function

1 个答案:

答案 0 :(得分:0)

这是我的解决方法

通过在函数内部移动变量,我能够在没有运行时错误的情况下获得预期的结果。

Private LastRow As Long
Private CellRow As Integer    ' create a variable to hold the cell row
Private x As Long, c As Long, s As Long, z As Long
Const CONTACT_START As Long = 13 ' Column E
Const COL_PER_CONTACT As Long = 2 ' Columns per Contact
Const CONTACT_DROPS As Long = 14 'Column G
Const COL_PER_DROPS As Long = 2 'Columns per Contact





Public Function callDate() As Date
s = CONTACT_START
c = CONTACT_START
x = CLng(addnewClient.lblRow.Caption)
z = LastRow
LastRow = Sheet3.Range("a" & Rows.count).End(xlUp).Row + 1
CellRow = ActiveCell.Row
With ThisWorkbook.Sheets("clientmenu")
        c = CONTACT_START
        x = CLng(addnewClient.lblRow.Caption)
        ' Look for first empty one
        Do Until IsEmpty(.Cells(x, c))
            c = c + COL_PER_CONTACT
        Loop
        .Cells(x, c) = addnewClient.contact.value
        '.Cells(x, c + 1) = Me.cdates1.Value
    End With
End Function