如何同步工作簿中的所有 Textbox1?

How to sync All Textbox1 in Workbook?

我的工作簿有五个 sheet 带有文本框。 Sheet1、Sheet2、……和 Sheet5。

下面的代码在每个 sheet 上。

Private Sub TextBox1_Change()

If Len(TextBox1.Value) = 0 Then
ActiveSheet.AutoFilterMode = False

Else
  If ActiveSheet.AutoFilterMode = True Then
  ActiveSheet.AutoFilterMode = False

End If

ActiveSheet.Range("A2:C" & Rows.Count).AutoFilter field:=1, Criteria1:="*" & TextBox1.Value & "*"
End If

End Sub

我想在所有 sheet 上同步 TEXTBOXES

例如,如果我在 Sheet1 的 TEXTBOX1 中键入文本,则相同的文本将在所有其他 sheet 的 TEXTBOX1 中输入。

而且我还想知道如何一次清除每个 sheet 上的 TEXTBOX

您可以在您的项目中添加模块并在其中添加此 Sub(如果需要,调整工作表和文本框的名称):

Sub SetText(txt As String)
    Worksheets("Sheet1").TextBox1.Text = txt
    Worksheets("Sheet2").TextBox1.Text = txt
    Worksheets("Sheet3").TextBox1.Text = txt
    Worksheets("Sheet4").TextBox1.Text = txt
    Worksheets("Sheet5").TextBox1.Text = txt
End Sub

然后,在每个 TextBox 的 Change 事件中添加这个

Private Sub TextBox1_Change()
    SetText Me.TextBox1.Text
End Sub

要清除所有文本,您可以设置 .TextBox1.Text = ""

1) 将以下代码放入项目的新模块中

Public dontDoThat As Boolean ' a public variable, visible throughout all your project you'll use to give way to synchronizing activity

Option Explicit

Sub Synchronize(txt As String, shtName As String)
    dontDoThat = True ' set your public variable to True and prevent subsequent TextBox1_Change() events to run it again

    Dim sht As Variant
    For Each sht In Array("Sheet1", "Sheet2", "Sheet3", "Sheet4", "Sheet5")
        If sht <> shtName Then Worksheets(sht).TextBox1.Text = txt 
    Next

    dontDoThat = False ' set your public variable to False and allow subsequent TextBox1_Change() events to run it 
End Sub

2) 按如下方式更改所有工作表中的 TextBox1_Change() 事件

Private Sub TextBox1_Change()
    If Not dontDoThat Then Synchronize Me.TextBox1.Text, Me.Name 'call Synchronize() only if your public variable allows it to

    ...
    (rest of your previous code follows)
    ...

End Sub

要清除所有文本框只需清除其中一个