用VBA修剪问题
所以下面的代码有时有时工作,有时它增加了我试图剪切出来的文本string的&符号(复制缓冲区)。
代码的要点是将string从正确的位置复制到&符号之前。 但是,在随机场景中,它仍会添加&符号。
Private Sub Block1_Enter() Application.ScreenUpdating = False Application.DisplayAlerts = False Dim MyData As New DataObject Dim this As String Dim oldxt As String oldtxt = Block1.Text If InStr(Block1.Text, "&") > 0 Then this = Trim(Right(Block1.Text, InStr(Block1.Text, "&") - 1)) Block1.Text = "End Date Copied" & this MyData.SetText this MyData.PutInClipboard Application.Wait (Now + #12:00:02 AM#) Block1.Text = oldtxt End If Application.ScreenUpdating = True Application.DisplayAlerts = True End Sub
有人可以尝试和解释为什么它有时工作,有时没有? 下面是一个图像,其中有两个例子,它不正确的工作
(注意澄清:下面显示的文本框的值是源值,而不是结果)
使用Mid$()
代替:
this = Trim$(Mid$(Block1.Text, InStr(Block1.Text, "&") + 1))
您现在正在从string的左侧获取&
的位置,然后使用此数字从string的右侧获取date; 相反,您应该从string的Len
中减去&
的Instr
值,以获得剩余的字符。 尝试这个:
Private Sub Block1_Enter() Application.ScreenUpdating = False Application.DisplayAlerts = False Dim MyData As New DataObject Dim this As String Dim oldxt As String oldtxt = Block1.Text If InStr(Block1.Text, "&") > 0 Then this = Trim(Right(Block1.Text, (Len(Block1) - InStr(Block1.Text, "&") - 1)) Block1.Text = "End Date Copied" & this MyData.SetText this MyData.PutInClipboard Application.Wait (Now + #12:00:02 AM#) Block1.Text = oldtxt End If Application.ScreenUpdating = True Application.DisplayAlerts = True End Sub
这些date特别是错误的原因是因为第二个date的字符长度比第一个date的字符长度短。