简体   繁体   中英

Using VBA in Outlook, how can I convert an Excel range to a table?

I am trying to convert an Excel range to a table using a VBA script run from Outlook.

This worked when run from Excel but not from Outlook:

ListObjects.Add(xlSrcRange, Range("A1:D10"), , xlYes).Name = "myTable"

I tried this next code in Outlook but it failed:

Dim excApp As Excel.Application
Set excApp = GetObject(, "Excel.Application")    
excApp.ListObjects.Add(xlSrcRange, Range("A1:D10"), , xlYes).Name = "myTable"

This code threw run-time error '1004' Method 'Range' of object '_Global' failed.

I want to know how to make the code work, but I also want to understand why my code failed so that I can learn from it. I appreciate any suggestions. Thanks!

This is because in Excel you already have a sheet open. The ActiveSheet is the default when you just stick Range("somerange") without specifying which sheet, workbook, or excel application object that range exists in. In outlook there is no such thing as activesheet and so it has no idea what you mean by that range.

You'll have to be more explicit:

Dim excApp As Excel.Application
Set excApp = GetObject(, "Excel.Application")  
Dim excWB as Object
Set excWB = excApp.Workbooks.Add  
excApp.ListObjects.Add(xlSrcRange, excWB.sheets("sheet1").Range("A1:D10"), , xlYes).Name = "myTable"

Or something along those lines

In short, an excel application has workbooks, workbooks have sheets, and sheets have ranges.

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