简体   繁体   English

使用工作表名称变量引用另一个工作表

[英]Reference Another Sheet Using a Variable for the Sheet Name

I would like to reference each sheet in this formula by specifying the sheet name with the variable, "sheetname". 我想通过使用变量“ sheetname”指定工作表名称来引用此公式中的每个工作表。 Does anyone know how to do this? 有谁知道如何做到这一点?

Sub PopulateRow()

Dim WS_Count As Integer
Dim I As Integer
Dim sheetname As String

WS_Count = ActiveWorkbook.Worksheets.Count

For I = 1 To WS_Count

    Worksheets(I).Activate
        sheetname = ActiveSheet.Name
    Worksheets(1).Cells(I, 1).Formula = "=sum('sheetname'!d:d)"

Next I

End Sub

You would pull the variable outside the quotes and concatenate with & . 您可以将变量放在引号之外,并与&串联。

Sub PopulateRow()

Dim WS_Count As Integer
Dim I As Integer


WS_Count = ActiveWorkbook.Worksheets.Count

For I = 1 To WS_Count

    Worksheets(1).Cells(I, 1).Formula = "=sum('" & Worksheets(I).Name & "'!d:d)"

Next I

End Sub

As a note I removed the sheet.Activate. 注意,我删除了工作表。激活。 It will slow down the code and is not needed if done properly. 它将减慢代码的速度,如果正确完成,则不需要此代码。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM