使用公式链接单元格填充摘要表的Excel VBA代码

时间:2017-08-17 15:10:31

标签: excel vba excel-vba formula offset

我正在尝试创建一个摘要表,其中包含7列的46行数据。因此,我将从46张纸中提取数据,并且将有7个不同的数据点。

我可以使用偏移功能来简化此代码,例如

Sub AutoFillSheetNames()
    Dim ActRng As Range
    Dim ActWsName As String
    Dim ActAddress As String
    Dim Ws As Worksheet

    On Error Resume Next

    Set ActRng = Application.ActiveCell
    ActWsName = Application.ActiveSheet.Name
    ActAddress = ActRng.Address(False, False)

    Application.ScreenUpdating = False

    xIndex = 0
    For Each Ws In Application.Worksheets
        If Ws.Name <> ActWsName Then
            ActRng.Offset(xIndex, 0).Value = "='" & Ws.Name & "'!" & ActAddress
            xIndex = xIndex + 1
        End If
    Next

    Application.ScreenUpdating = True
End Sub

我想链接实际的单元格,以便它们可以自动更新并且需要VBA,因为它将针对具有不同标签名的许多不同的excel工作簿进行。此处发布的代码适用于,例如,我将摘要表上的单元格F2链接到第一张48张纸上的F2,然后将剩余的47个单元格的公式正确输入到F48。但是,当我想将摘要表中的单元格H2链接到第一张表格中的G7时,我应该在上面的代码中更改哪些内容?

1 个答案:

答案 0 :(得分:0)

我真的无法理解你想要完成的事情。下面的代码将链接摘要表中每个工作表的第一行(即A1:G1)中的7个单元格。表格将与表格一样多。但我不知道这是不是你真正想要的。

Sub AutoFillSheetNames()
    Dim CurrWorkBK As Workbook
    Dim CurrSheet As Worksheet
    Dim TheOtherSheets As Worksheet
    Dim MyRow As Long
    Dim MyCol As Long

    Set CurrWorkBK = ThisWorkbook
    Set CurrSheet = CurrWorkBK.Worksheets("Summary")

    MyRow = 1
    For Each TheOtherSheets In CurrWorkBK.Worksheets
        If TheOtherSheets.Name <> CurrSheet.Name Then
            For MyCol = 1 To 7
                CurrSheet.Cells(MyRow, MyCol).Value = "='" & TheOtherSheets.Name & "'!" & TheOtherSheets.Cells(1, MyCol).Address
            Next MyCol
            MyRow = MyRow + 1
        End If
    Next
End Sub