Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.9k views
in Technique[技术] by (71.8m points)

excel - Copy Paste macro is inducing 'grouped'-worksheet functionality?

I am getting an error I can't figure out:

After I run the macro below, two certain string values are pasted into the same two cells in ALL sheets, although I am sure that the sheets are not grouped or do not contain individual code of their own. Specifically, the items "B12" and "B25" are pasted on all pages at the same cells (A29 and A30) (See code). "B12" and "B25" have nothing to do with a cell location but are just identifiers unique to my application. They are values which are copied+pasted from one sheet into another. If it is a copy+paste error in the code, then I would expect all the items to have the same error because the "algorithm" subroutine is called for every sheet.

Sometimes, this also occurs without execution of the macro. And when I try to edit my workbook back to how it was before fields were pasted over (by clicking each cell and typing what used to be there), it still makes those changes to all sheets, even though I am sure they are not grouped or running code.

' Title: DSR AutoFill Macro

Sub autofill_DSR()

' Variable Declarations:

Dim x_count As Long
Dim n As Long
Dim item_a As String
Dim item_b As String
'Dim test_string As String

' Variable Initializations:

x_count = 0
Process_Control_NumRows = 15
Electrical_NumRows = 8
Environmental1_NumRows = 17
Env2_Regulatory_NumRows = 14
FIRE_NumRows = 15
Human_NumRows = 16
Industrial_Hygiene_NumRows = 16
Maintenance_Reliability_NumRows = 10
Pressure_Vacuum_NumRows = 16
Rotating_n_Mechanical_NumRows = 11
Facility_Siting_n_Security_NumRows = 10
Process_Safety_Documentation_NumRows = 3
Temperature_Reaction_Flow_NumRows = 18
Valve_Piping_NumRows = 22
Quality_NumRows = 10
Product_Stewardship_NumRows = 20
fourB_Items_NumRows = 28
'test_string = "NN"

' Main Data Transfer Code:

Sheets(Array("SUMMARY P.1", "SUMMARY P.2", "Process Control", _
"Electrical", "Environmental1", "Env.2 - Regulatory", "FIRE", _
"Human", "Industrial Hygiene", "Maintenance_Reliability", _
"Pressure_Vacuum", "Rotating & Mechanical", _
"Facility Siting & Security", "Process Safety Documentation", _
"Temperature-Reaction-Flow", "Valve-Piping", "Quality", _
"Product Stewardship", "4B ITEMS")).Select              'Create Array of all Sheets

'Sheets(Array("Sheet1", "Sheet2", "Sheet3")).Select     ' For testing

' Process Control Sheet:

    For n = 0 To (Process_Control_NumRows - 1)  'Cycle 16 times for each
                                                'item row in process controls tab
        Sheets("Process Control").Activate      'Choose specific sheet
        Range("D15").Select                     'Choose starting cell of "Yes" column

        Call Module2.algorithm(n, x_count)      'Call on subroutine (see algorithm code)

    Next n                                      'increment index to account for offset

' Electrical Sheet:

    For n = 0 To (Electrical_NumRows - 1)

        Sheets("Electrical").Activate
        Range("D15").Select

        Call Module2.algorithm(n, x_count)

        If (x_count > 21) Then                  'Abort autofill if too many items to hold
            Sheets("SUMMARY P.1").Activate      'on both summary pages put together (21 count)
            GoTo TooMany_Xs
        End If

    Next n

This continues for all the sheets...

' 4B ITEMS Sheet:

    For n = 0 To (fourB_Items_NumRows - 1)

        Sheets("4B ITEMS").Activate
        Range("D16").Select         ' NOTE: Starting cell is "D16"

        Call Module2.algorithm(n, x_count)

        If (x_count > 21) Then
            Sheets("SUMMARY P.1").Activate
            GoTo TooMany_Xs
        End If

    Next n

If (x_count > 5) Then               'Bring user back to last logged sheet

    Sheets("SUMMARY P.2").Activate

Else

    Sheets("SUMMARY P.1").Activate

End If

TooMany_Xs:
 If Err.Number <> 0 Then
    Msg = "you put more than 21 Items on the Summary Pages." & Chr(13) & _
        "Consider editing your DSR or taking some other action."
    MsgBox Msg, , "Error", Err.HelpFile, Err.HelpContext
 End If

End Sub

And then this following macro is located in Module2:

Sub algorithm(n As Long, x_count As Long)

        'If an "x" or "X" is marked in the "Yes" column,
        'at descending cells down the column offset by the for loop index, n

        If (ActiveCell.Offset(n, 0) = "x" Or ActiveCell.Offset(n, 0) = "X") Then

            item_a = ActiveCell.Offset(n, -3).Value     ' Store Letter value
            item_a = Replace(item_a, "(", "")           ' Get rid of "(", ")", and " " (space)
            item_a = Replace(item_a, ")", "")           ' characters that are grabbed
            item_a = Replace(item_a, " ", "")

            item_b = ActiveCell.Offset(n, -2).Value     ' Store number value
            item_b = Replace(item_b, "(", "")           ' Get rid of "(", ")", and " " (space)
            item_b = Replace(item_b, ")", "")           ' characters that are grabbed
            item_b = Replace(item_b, " ", "")

            x_count = x_count + 1                       ' increment the total x count

            If (x_count > 5) Then                       ' If there are more than 5 "x" marks,

                Sheets("SUMMARY P.2").Activate          ' then continue to log in SUMMARY P.2
                Range("A18").Select                     ' Choose "Item" column, first cell
                ActiveCell.Offset((x_count - 6), 0).Value = (item_a & item_b)

                'Insert cocatenated value of item_a and item_b
                '(for example "A" & "1" = "A1")
                'at the cells under the "Item" column, indexed by x_count

            Else                                        ' If there are less than 5 "x" marks,

                Sheets("SUMMARY P.1").Activate          ' log in SUMMARY P.1
                Range("A25").Select
                ActiveCell.Offset((x_count - 1), 0).Value = (item_a & item_b)

            End If

        End If

End Sub

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

By selecting all the sheets in your array, you are grouping them, and anything you write to a cell in any sheet will be written to all sheets.

This is the culprit:

Sheets(Array("SUMMARY P.1", "SUMMARY P.2", "Process Control", _
"Electrical", "Environmental1", "Env.2 - Regulatory", "FIRE", _
"Human", "Industrial Hygiene", "Maintenance_Reliability", _
"Pressure_Vacuum", "Rotating & Mechanical", _
"Facility Siting & Security", "Process Safety Documentation", _
"Temperature-Reaction-Flow", "Valve-Piping", "Quality", _
"Product Stewardship", "4B ITEMS")).Select

The fact that your issue occurs even if the code you posted hasn't been run makes me think there is something else going on after you've selected all the sheets.

Note that selecting and activating are a really bad idea. Declare variables for the objects you want to work with and interact with them that way instead of selecting them.

Here is a quick example of how you can loop through all the sheets in a workbook and modify them without selecting or activating. You can modify your code to use this pattern:

Sub LoopThroughAllSheets()
    Dim wb As Workbook
    Dim ws As Worksheet

    Set wb = ThisWorkbook

    For Each ws In wb.Sheets
        ws.Range("D15").Value = ws.Name
    Next ws
End Sub

Please read the following to get you started on writing cleaner, more efficient VBA code:


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...