interlink excel工作簿中的单元格

问题描述 投票:0回答:2

我有Excel工作簿,其中有4个工作表,其中有两个单元格名称开始日期和结束日期,其值应该在所有4个工作表中相同,我想如果我更改任何工作表中的值,其他三个工作表会自动更新那个价值观。反之亦然。

excel vba
2个回答
3
投票

如果任何一个单元格发生更改,请使用Workbook_SheetChange事件更新每个工作表上的相同单元格。


例如,如果每个工作表都具有命名范围start_dateend_date(其范围仅限于该工作表),则对任何工作表上的任何start_dateend_date范围所做的更改将更新所有其他工作表上的相应范围。

Option Explicit

Private Sub Workbook_SheetChange(ByVal Sh As Object, ByVal Target As Range)
    On Error GoTo SafeExit
    Application.EnableEvents = False
    Dim ws As Worksheet

    With Sh
        If Not Intersect(Target, .Range("start_date")) Is Nothing Then
            For Each ws In Worksheets
                ws.Range("start_date").Value = Target.Value
            Next ws
        End If
        If Not Intersect(Target, .Range("end_date")) Is Nothing Then
            For Each ws In Worksheets
                ws.Range("end_date").Value = Target.Value
            Next ws
        End If
    End With

SafeExit:
    Application.EnableEvents = True
End Sub

如果您按地址而不是通过定义的名称引用单元格,则此类内容可能有效:

Private Sub Workbook_SheetChange(ByVal Sh As Object, ByVal Target As Range)
    On Error GoTo SafeExit
    Application.EnableEvents = False
    Dim ws As Worksheet

    With Sh
        ' "A1" is the start date, change as needed
        If Not Intersect(Target, .Range("A1")) Is Nothing Then
            For Each ws In Worksheets
                ws.Range("A1").Value = Target.Value
            Next ws
        End If
        ' "B1" is the end date, change as needed
        If Not Intersect(Target, .Range("B1")) Is Nothing Then
            For Each ws In Worksheets
                ws.Range("B1").Value = Target.Value
            Next ws
        End If
    End With

SafeExit:
    Application.EnableEvents = True
End Sub

此代码位于VBA编辑器中的ThisWorkbook模块中。


0
投票

您不需要VBA,而是命名范围。将光标放在输入单元格中,例如E5,用于start_date,然后单击命名范围框(位于工作表网格的左上角,直接位于A列上方)。在start_date上输入E5并点击Enter。现在,单元格E5被命名为start_date。如果在工作簿中的任何其他位置使用=start_date,它将引用单元格E5的当前内容。如果要以任何方式编辑命名范围,请转到功能区菜单FORMULAS -> Name Manager

如果你想用VBA做这个只是为了学习VBA,我建议你去VBA课程。 Udemy有一些好的,经常以10美元左右的价格出售,我相信其他地方也有很多免费资源。

© www.soinside.com 2019 - 2024. All rights reserved.