简体   繁体   中英

Find Last Column used in excel sheet using VBA in Microsoft Word

I need to operate on an excel sheet using VBA from MS Word.

I wasn't able to understand why I get error when I try to catch LastCol value:

Dim mXL As Object
Dim mWBook As Object
Dim mSheet As Object
Dim C As Long, R As Long
Dim LastRow As Long, LastCol As Long

Set mXL = CreateObject("Excel.Application")
mXL.Visible = True
Set mWBook = mXL.Workbooks.Open("c:\test\test.xlsx")
Set mSheet = mWBook.sheets(1)
LastCol = mSheet.Cells(1, mSheet.Columns.Count).End(xlToLeft).Column 'THIS ISN'T WORKIMG
LastCol = mSheet.Cells(1, 1).End(xlToRight).Column 'This also gives error

You're using late-binding, so Word doesn't know what xlToLeft and xlToRight are, because those are from the Excel object model.

Add the following:

Const xlToLeft As Long = -4159
Const xlToRight As Long = -4161

based on the corresponding values from the XLDirection enum.

As @BigBen mentioned you can't use Excel's enum with late bound. Use the value of enums instead ( https://docs.microsoft.com/en-us/office/vba/api/excel.xldirection )

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