Search code examples
variablesexcel-indirectpasting

Pasting from a variable defined range


New to vba and I am having difficulties with pasting. Here is my code:

Dim xtext As String

Dim ytext As String

x = ActiveSheet.Range("A8")

y = ActiveSheet.Range("A9")

Range("A6").Select Selection.Copy

Range("xtext:ytext").Select Selection.Paste

Endsub

Cell A8 (which is variable x) value is B2, and Cell A9 (which is variable y) is B10. I thought it would paste from B2:B10 but instead is pasting into columns x:y. So I kind of want it to work like an indirect formula? I am not sure if this is even close to what I want?

Thanks!


Solution

  • Rename your variables - "x" & "y" are bad as they are not indicative of what they hold. This is particularly true in Excel, where a single letter also refers to a column - which is what has happened here; you have posted to the range "X:Y", which is just the selection of all of column X, and all of column Y.

    Your whole code together becomes [note that I changed your definition of x and y to be ranges, not text strings, and as such had to make them equal to your A8 & A9 by "set = to"] [assuming in your spreadsheet that cell A8 says "B2", and A9 says "B10"]:

    Sub test()
    
    Dim x As Range
    Dim y As Range
    
    Set x = ActiveSheet.Range("A8")
    Set y = ActiveSheet.Range("A9")
    
    
    Range("A6").Select
    Selection.Copy
    
    Range(x.Text, y.Text).Select
    ActiveSheet.Paste
    
    End Sub
    

    Edited to now refer indirectly to what is entered into cells A8 & A9