且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何从Excel调用VBA函数

更新时间:2022-12-03 11:08:34

您可以在工作表内使用 Worksheet_Change 事件.在VBE内部,选择工作表,然后从左侧下拉列表中选择 Workhseet ,并从右侧选择 Change .

You can use the Worksheet_Change event inside the sheet. Inside the VBE, select the sheet and choose Workhseet from the left drop-down and Change from the right.

输入以下代码:

Option Explicit

Private Sub Worksheet_Change(ByVal Target As Range)

If Target.Address = "$A$1" Then 'assumes user input cell is A1

    With Application
        .ScreenUpdating = False
        .EnableEvents = False
    End With

    On Error GoTo ErrTrap

    Target.Value = isValidTime(Target.Value)

End If

KeepMoving:

    With Application
        .ScreenUpdating = True
        .EnableEvents = True
    End With

    Exit Sub 

ErrTrap:

    MsgBox Err.Number & Err.Description
    Resume KeepMoving


End Sub

Public Function isValidTime(myText) As String

Dim regEx

Set regEx = New RegExp   'Regular expression object

regEx.Pattern = "^[0-9]+([:]+[0-9]+)*$"  ' Set pattern.

If regEx.test(myText) Then

    isValidTime = myText

Else
    isValidTime = "Null"

End If

End Function