简体   繁体   English

在 Microsoft Word 中使用 VBA 查找 excel 工作表中使用的最后一列

[英]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.我需要使用 MS Word 中的 VBA 对 excel 工作表进行操作。

I wasn't able to understand why I get error when I try to catch LastCol value:当我尝试捕获 LastCol 值时,我无法理解为什么会出错:

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.您正在使用后期绑定,所以 Word 不知道xlToLeftxlToRight是什么,因为它们来自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.基于XLDirection枚举中的相应值。

As @BigBen mentioned you can't use Excel's enum with late bound.正如@BigBen 提到的,您不能使用 Excel 的枚举与后期绑定。 Use the value of enums instead ( https://docs.microsoft.com/en-us/office/vba/api/excel.xldirection )改用枚举值( https://docs.microsoft.com/en-us/office/vba/api/excel.xldirection

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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