【问题标题】:How to force ControlSource updating (excel userforms)如何强制 ControlSource 更新(excel 用户表单)
【发布时间】:2013-01-22 16:08:37
【问题描述】:

在我的 Excel VBA 用户表单上有一个文本框,用户应在其中输入 dd-mm-yy 格式的日期。如果输入为09-22-13,则应更新为22-09-2013。此文本框的 ControlSource 属性设置为单元格的地址;这个单元格的值也应该变成22-09-2013

我尝试过的所有事件处理程序的问题是 ControlSource 的值在触发处理程序之前得到更新,除非我硬编码它的地址,否则我无法更改 ControlSource 的值(这是我想避免的) .

你能帮忙吗?谢谢。

Private Sub TextBox_MyDate_BeforeUpdate(ByVal Cancel As MSForms.ReturnBoolean)
    TextBox_MynDate.Value = Format(TextBox_MyDate.Value, "dd/mm/yyyy")
    ' TextBox_MyDate.ControlSource.Value = TextBox_MyDate.Value does not compile
    DoEvents
End Sub

【问题讨论】:

  • 意识到我忘记给你投票了 :) +1

标签: vba datetime excel event-handling userform


【解决方案1】:

这里有一点需要考虑,controlsource updateevent order 似乎无法更改,因此您可以尝试在textbox event 之前添加worksheet_change 事件,因为前者在textbox event 存在之前触发..

Reference:

  • 它说,如果您使用 ContolSource,那么每次相关单元格更改时文本框都会刷新,但请注意,反之亦然。更改一个文本框 & 单元格将改变

【讨论】:

  • 从 VBA 更改文本框值(使用 TextBox_MynDate.Value = line)似乎不会更改单元格值,否则我猜我会有无限递归。
  • worksheet_change 事件似乎是避免对单元格地址进行硬编码的唯一方法,但我最终还是硬编码了它,因为就我而言,它更简单。
  • @YuccaV 用Sheet change event 解决无限循环,你可以设置Events to false
【解决方案2】:
   Private Function GetCtrlSourceStr$()
        On Error Resume Next
        GetCtrlSourceStr = wCtrl.ControlSource
   End Function

' ' 如果 Form 已卸载并且 Sheet FoFiCriteria 中的值通过编辑工作表而更改 ' 表单文本框或复选框将不会链接到这些更改.. ' 显示或隐藏的表单仍将与其控制源同步 ' 在表单打开但 FoFiCriteria 不是活动工作表时工作 ' 这些 ControlSource 字符串必须为 ,, SHeetName!B14 .. FoFiCriteria!L9 ' 来自 ' RaAdd = ra(3, Ci).Address(False, False, , True) ' .ControlSource = Mid(RaAdd, InStr(RaAdd, "]") + 1)

' 所以在表单上编辑应该链接到其工作表上的控制源范围 '所以我们需要 '

Sub ReGetCtrlSources()
   For Each wCtrl In frd.Controls
        If GetCtrlSourceStr <> "" Then
       wCtrl.Value = Range(wCtrl.ControlSource).Value
    wCtrl.BackColor = Range(wCtrl.ControlSource).Interior.Color
       End If

   Next wCtrl

结束子

' 添加激活 私有子 UserForm_Activate()

   ReGetCtrlSources

   End Sub

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-10-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-07-03
    相关资源
    最近更新 更多