首页 > 解决方案 > 是否可以转换可以在 vbnet 中使用的 vba 代码?

问题描述

再会,

我有我从 vba excel 使用的这段代码

Private Sub txtSTime_Change()

Dim ascii   As Integer
Dim h       As Integer
Dim m       As Integer
Dim n       As Integer

    n = Len(txtSTime.Value)
    
    If n = 0 Then Exit Sub
    
        ascii = Asc(Right(txtSTime.Value, 1))
        ' Validate the hour is 2 digits from 01 to 23.
        If n = 2 And ascii <> 58 And CharCode <> 8 Then
            h = CInt(Left(txtSTime.Value, 2))
            If h < 0 Or h > 23 Then
                MsgBox "Invalid hour " & h & vbLf & "Hours are from 00 to 23."
                txtSTime.Value = ""
                Me.txtSTime.SetFocus
                Exit Sub
            End If
        End If
        
        ' Validate the month is 2 digits from 01 to 12.
        If n = 5 And ascii <> 58 And CharCode <> 8 Then
            m = CInt(Mid(txtSTime.Value, 4, 2))
            If m < 0 Or m > 59 Then
                MsgBox "Invalid minute " & m & vbLf & "Minutes are from 00 to 59."
                txtSTime.Value = Left(txtSTime.Value, 3)
                Me.txtSTime.SetFocus
                txtSTime.Value = ""
            End If
        End If

End Sub

Private Sub txtSTime_KeyDown(ByVal KeyCode As MSForms.ReturnInteger, ByVal Shift As Integer)

    CharCode = 0
    n = KeyCode
    
    Select Case KeyCode
        Case 8, 10, 13, 46: CharCode = KeyCode  ' Process these control characters: BS, LF, CR and Delete.
        Case 48 To 57, 96 To 105                ' Display numbers and forward slahes from keyboard and number pad.
        Case 186 And Shift = 1                  ' Display the colon.
        Case Else: KeyCode = 0                  ' Erase all other input.
    End Select

End Sub

Private Sub txtSTime_KeyUp(ByVal KeyCode As MSForms.ReturnInteger, ByVal Shift As Integer)

Dim char    As String
Dim n       As Integer

    n = Len(txtSTime)
    
    If n > 0 Then char = Right(txtSTime, 1)
    
    Select Case KeyCode
        Case 48 To 57, 96 To 105
            ' Automatically add the colon after the day and month.
            If n = 3 Then
                txtSTime.Value = Left(txtSTime.Value, n - 1) & ":" & char
            End If
        Case 183 And Shift = 1
            ' Display the colon only after the minutes.
            If n <> 3 Then
                txtSTime.Value = Left(txtSTime.Value, n - 1)
            End If
    End Select

End Sub

它的功能是每当我在 txtSTime 文本框中输入数字时,它都会自动将数字更改为 24 小时时间格式。示例我输入“1220”它会自动变为“12:20”

我尝试在 vb.net 中寻找相同的功能,但似乎找不到任何东西。

是否可以将 vba excel 中的代码转换为可在 vb.net 中使用的代码?

标签: vbavb.nettime

解决方案


我也来自 VBA,现在我正在练习 VB.net 和 C# 现在不必那么复杂。至于您的解决方案,您需要注意两件事。首先让用户输入数字。您可以参考 VB.net 需要文本框只接受数字

其次,您可以使用拆分功能来格式化您的文本

Dim txt As String = txtSTime.Text
Dim Result As String = txt.Substring(0, 2) & ":" & txt.Substring(3, 2)
txtSTime.Text = Result

推荐阅读