简体   繁体   中英

VBA Transposing a dynamic range in excel

Basically I have a dynamic range that will always be in columns A:C in sheet 1. I'm trying to write a personal macro that copies the dynamic range and transposes this onto sheet 2 to allow mail merge to be able to read row 1 as mail merge fields.

Currently the error appears at this line:

Set sourceRange = ActiveSheet.Range(Cells(1, 1), Cells(lastRow, 1))

The entire code is listed below. There is probably a simple mistake I'm missing or perhaps even an easier way to achieve my desired result, however this is what I currently have come up with.

Sub TrasposeData()
'
' TrasposeData Macro
' Takes the data from sheet one and transpose it to sheet 2 to allow for mail merge compatibility.

Sheet1.Activate

Dim sourceRange As Range
Dim targetRange As Range
Dim lastRow As Long

lastRow = WorksheetFunction.CountA(Range("A:A"))
Set sourceRange = ActiveSheet.Range(Cells(1, 1), Cells(lastRow, 1))

Sheet2.Activate

Set targetRange = ActiveSheet.Cells(1, 1)

Sheet1.Activate

sourceRange.Copy

Sheet2.Activate

targetRange.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks:=False, Transpose:=True

' Keyboard Shortcut: Ctrl+t
'
    Application.Run "PERSONAL.XLSB!TrasposeData"
    ActiveWindow.Close
End Sub

Any help would be much appreciated.

So I spent A little more time researching today and finally got it to work. the script is posted below:

Sub TransposeData()
'
' TransposeData Macro
' Traspose the data on sheet1 to sheet2 to allow for mail merge
'

Sheets("Sheet1").Select

Dim sourceRange As Range
Dim lastRow As Long

lastRow = Cells(Rows.Count, "A").End(xlUp).Row

Set sourceRange = ActiveSheet.Range("A1:C" & lastRow)

sourceRange.Copy

Sheets("Sheet2").Select

Cells(1, 1).PasteSpecial Paste:=xlPasteValues, Operation:=xlNone,    SkipBlanks:=False, Transpose:=True

' Keyboard Shortcut: Ctrl+Shift+T
'
End Sub

Thanks El Scripto and KazJaw for your suggestions, much appreciated.

In your code, doing:

 lastRow = WorksheetFunction.CountA(Range("A:A"))
 Set sourceRange = ActiveSheet.Range(Cells(1, 1), Cells(lastRow, 1))

counts the number of none empty cells, but it may not give you the last cell (logical error). Like KazJaw wrote above, it might be also the reason for a possible error.

A better way would be to use (it replaces the above two lines):

  Set SourceRange = ActiveSheet.Range(Cells(1, 1), _
                         Cells(ActiveSheet.UsedRange.Rows.Count, 1))

Try it, and if it fails, please post the error message.

A simple way to copy the error is just click on the error messagebox, then press CTRL+C, and it should copy the error details in plain text to the clipboard, so you could paste it here.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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