简体   繁体   English

Excel VBA遍历工作表并更改单元格以反映摘要工作表

[英]Excel VBA iterate through sheets and change cells to reflect summary sheet

So I am new to VBA and trying to write a piece of code to increase my efficiency. 因此,我刚接触VBA,并尝试编写一段代码来提高效率。 I am trying to iterate through 66 different sheets (named 1, 2, 3, etc.) and change the values of certain cells to reflect values listed in a summary sheet. 我试图遍历66个不同的工作表(命名为1、2、3等),并更改某些单元格的值以反映摘要表中列出的值。 I want to essentially iterate down by one row in the summary sheet for every sheet in the workbook. 我实质上想对工作簿中的每个工作表在摘要工作表中逐行向下进行迭代。 I tried to record a macro and write something based on that, but my solution doesn't work. 我试图记录一个宏并在此基础上编写一些东西,但是我的解决方案不起作用。 Any help would be appreciated! 任何帮助,将不胜感激!

*Updated code, but something still isn't working. *更新了代码,但仍然无法正常工作。 I think it may be because I am not properly selecting the sheet that I want to make the changes in? 我认为可能是因为我没有正确选择要进行更改的工作表?

**Edit2: The code works now- I guess I had to put the first 66 sheets at the beginning of the workbook, the macro was trying to iterate through other protected sheets. ** Edit2:该代码现在可以正常工作-我想我必须将前66张纸放在工作簿的开头,宏正在尝试遍历其他受保护的纸。 Thanks for the help. 谢谢您的帮助。

Sub Macro6()
Dim WS_Count As Integer
Dim i As Integer
'Set WS_Count to the number of sheets with CPT data
WS_Count = 66
For i = 1 To WS_Count
Sheets(i).Activate
Sheets(i).Select
Range("A2").FormulaR1C1 = "='Data Input'!R[" & (17 + i) & "]C[1]"
Range("F6").FormulaR1C1 = "='Data Input'!R[" & (14 + i) & "]C[4]"
Range("H6").FormulaR1C1 = "='Data Input'!R[" & (14 + i) & "]C[3]"
Range("I6").FormulaR1C1 = "='Data Input'!R[" & (14 + i) & "]C[3]"
Range("L6").FormulaR1C1 = "='Data Input'!R[" & (14 + i) & "]C[8]"
Range("M6").FormulaR1C1 = "='Data Input'!R[" & (14 + i) & "]C[9]"
Next
End Sub
Range("A2").FormulaR1C1 = "='Data Input'!R["& (17+i) & "]C[1]"

Etc. 等等。

No need to select the cells before adding the formula 在添加公式之前无需选择单元格

EDIT: try not using RC notation (you might need to adjust the numbers a little) 编辑:尝试不使用RC表示法(您可能需要稍微调整一下数字)

Sub Macro6()
    Const WS_Count As Long = 66 'number of sheets with CPT data
    Dim i As Long

    For i = 1 To WS_Count
        With Sheets(i)
            .Range("A2").Formula = "='Data Input'!A" & (17 + i)
            .Range("F6").Formula = "='Data Input'!D" & (14 + i)
            .Range("H6").Formula = "='Data Input'!C" & (14 + i)
            .Range("I6").Formula = "='Data Input'!C" & (14 + i)
            .Range("L6").Formula = "='Data Input'!H" & (14 + i)
            .Range("M6").Formula = "='Data Input'!I" & (14 + i)
        End With
    Next
End Sub

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

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