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
720 views
in Technique[技术] by (71.8m points)

vba - Variable not being stored in the code when sheet changes

I'm quite new to coding and have encountered a probably very trivial issue. When I run the code line by line in the 'Trade_Sheet' tab, the variable Date_range is picked up correctly as a date previously copied, and updated for 7 days later. However the problem comes when I run the macro in the main tab 'Share_Calc_Tab' where the macro is situated. If I do so, it seems like the variable Date_range sets to 0, and while the rest of the operation is performed, the date will be missing.

The code is below:

Sub Audit_Trade()

    Dim Trade_Sheet As Worksheet
    Dim Share_Calc_Tab As Worksheet
    Dim lastrow As Long
    Dim Date_range As Date

    Set Trade_Sheet = ThisWorkbook.Worksheets("Trades")
    Set Share_Calc_Tab = ThisWorkbook.Worksheets("End Share Calc (ESC) GLOBAL")

    Application.ScreenUpdating = False

    With Trade_Sheet

        lastrow = .Cells(.Rows.Count, "A").End(xlUp).Row
        Date_range = Cells(lastrow, 1).Offset(-27, 0).Value
        Cells(lastrow + 2, 1).Value = Date_range + 7

    End With

    Share_Calc_Tab.Activate
    Range("Trade_Instruction_Daily").Copy
    Trade_Sheet.Activate
    Cells(lastrow + 3, 1).Select
    Selection.PasteSpecial Paste:=xlPasteFormats
    Selection.PasteSpecial Paste:=xlPasteValues
    Application.CutCopyMode = False

    Share_Calc_Tab.Activate
    Range("B22").Select

    Application.ScreenUpdating = True

End Sub

Any help will be much appreciated. Thanks all!

See Question&Answers more detail:os

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

1 Answer

0 votes
by (71.8m points)

The problem is that you do not define the worksheet correctly. See the points(dots) here:

With Trade_Sheet
    lastrow = .Cells(.Rows.Count, "A").End(xlUp).Row
    Date_range = .Cells(lastrow, 1).Offset(-27, 0).Value
    .Cells(lastrow + 2, 1).Value = Date_range + 7
End With

In your code, you are missing 2 of them: enter image description here

Thus, the Cells() refers to the ActiveSheet, and not to the Trade_Sheet. In general, Activate and Select are considered a bad practice in , thus it is a good idea avoid them:


For what is worth, this is probably the most common error in , thus you can be proud of yourself for reaching it. I guess that almost every VBA person has experienced it at least once.


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

...