Excel工作表相互依赖/镜像

时间:2014-03-11 23:30:16

标签: excel vba

假设我在Excel中有三张纸。工作表1是主工作表,工作表2和3包含不同的信息集,这些信息具有相同的标题,这些标题将提供给主工作表中的表格。是否有办法使我可以编辑表1中的信息,而表2将更改,反之亦然,以便我可以编辑表2中将更新主表单的信息?

1 个答案:

答案 0 :(得分:1)

您可以通过在主表单中使用Vlookup公式来解决此问题。这样,如果您更改了表2和表3中的任何内容,Master将自动更新。 如果用户更改了主表中的任何内容,则必须在VBA中构建逻辑。一种方法是格式化主表单,以便有一些东西可以帮助VBA知道编辑单元格中的公式应该是什么,并且还可以知道数据应该来自何处。松散地可以像这样设置主表:

  • 第1行是隐藏的,包含模板公式
  • 第2行被隐藏并且完全为空(这样可以减少过滤问题)
  • 第3行包含标题
  • 第4行和第4行包含使用第1行中定义的公式
  • 的数据
  • 在主工作表上添加更改事件,以查看更改的单元格是否具有公式。如果是这样,它将检查模板公式以识别数据应该来自何处。然后,它将使用在主工作表中输入的新值更新工作表2或3中的单元格。在此之后,它将使用模板行中的公式覆盖在主表中手动输入的值。

这里最重要的工作就是编写一个解析器,了解vlookup将从哪个单元中获取它的值。

我忽略的一件事是,如果用户一次粘贴多个单元格,则仅触发CHANGE事件。然后TARGET将包含多个行或列。

所以这是使用上述想法的某种骨架......

Option Explicit

Dim ChangeEventDisabled  As Boolean           'Flag for disabling the Change event

Public Sub Disable_ChangeEvent()
    ChangeEventDisabled = True
End Sub
Public Sub Enable_ChangeEvent()
    ChangeEventDisabled = False
End Sub


Sub Worksheet_Change(ByVal Target As Range)
Dim updatedValue As Variant
Dim SourceCell As Range


    'While the MasterSHeet is populated intially, we don't want this event to do anything
    If ChangeEventDisabled Then
        'There are chenges being done in teh sheet that should not trigger updates of the source-sheets.
    Else
        'Only run the code if it was a data-cell that was changed
        If Target.Row > 3 Then
            'We are in the rows containg data
            'Did the changed cell contain a Vlookup formula before the user changed the cells value?
            If UCase(Cells(1, Target.Column).Formula) Like "=VLOOKUP(*" Then
                'A vlookup normally populates this cell.
                'To know from where the data normally comes, I will need to put back the formula in the changed cell.
                'So, first save the new value that we will write in the source cell
                updatedValue = Target.Value
                'Insert the formula again in the cell
                'As we will now CHANGE a cell in the Masterr sheet, a Change event will trigger. Disable it temporarily
                Disable_ChangeEvent
                Cells(1, Target.Column).Copy Destination:=Target
                Enable_ChangeEvent
                'Find out from which cell the data is being fetched by the Vlookup
                Set SourceCell = MyMagicParsing(Target)
                'Update the source-cell with the new value
                SourceCell.Value = updatedValue
            End If
        End If
    End If

End Sub


Function GetSourceCell(Target As Range) As Range
'This function should decipher the formula in the cell Target, and figure out from where
'the data is actually coming. It shoudl return the range which is the source of the data.
'As I dont know how to do that quickly, I just hardcode the cell that is the source.
    GetSourceCell = Worksheets("Sheet2").Cells(67, 3)
End Function