0

So normally when using the VBA editor, code autosuggests from available methods.properties for whatever object your referencing. I'm trying to pull data from an excel sheet into a word document using a macro on the word doc, but whenever I try to use worksheets.activate, no autosuggestion for activate comes up, leading me to think it's not actually activating. Neither can I use it from a VBA script in excel.

My script is still in it's beginning stages, but here it is so far:

Sub Populate()
 Dim doc As Document
 Set doc = ActiveDocument
 
 Dim appXL As excel.Application
 Set appXL = CreateObject("excel.Application")
 
 Dim partnerNames As excel.Workbook
 Dim ihmNames As excel.Workbook
 Set partnerNames = appXL.Workbooks.Open("D:/Database/Imports and Exports/Funder Credit Lists/2022-01 Partners.csv")
 Set ihmNames = appXL.Workbooks.Open("D:\Database\Imports and Exports\Funder Credit Lists\2022-01 IHM.csv")
 
 appXL.Worksheets(Left(partnerNames.Name, Len(partnerNames.Name) - 4)).Activate
 
 Dim lastRow As Long
 lastRow = appXL.Cells.Find(What:="*", After:=Range("C1"), SearchOrder:=xlByRows, searchDirection:=xlPrevios).Row
 appXL.Range("A1").Resize(lastRow, 3).Select
 
 'Insert Hero Names
 Dim hero As Range
 Set hero = doc.Range(Start:=doc.Bookmarks("Hero").Start, End:=doc.Bookmarks("Hero").End)
 hero.InsertAfter ("IT WORKS!!!")
 
End Sub

the "lastRow = appXL.Cells....." is causing a type mismatch, which I believe is being caused by the fact that appXL.Cells refers to the active sheet, and the ActiveDocument is a word doc, and not a sheet. So that leads me to activating the sheet, but trying to do so causes the error "Subscript out of range," even if I explicitly type the sheet name.

Any pointers are appreciated, thanks.

4

3 回答 3

0

看来您只需要在 Word VBA 中添加 Excel COM 引用即可获得自动建议。从Tools菜单中选择References显示References对话框。References 对话框显示向操作系统注册的所有对象库。滚动浏览要引用其对象库的应用程序的列表。选中复选框的引用由您的项目使用;未选中的不使用,但可以添加。Available ReferencesReferences对话框的框中选择对象库引用并选择OK。您的 Visual Basic 项目现在具有对应用程序对象库的引用。如果你打开Object Browser(按F2)并选择应用程序的库,它显示所选对象库提供的对象,以及每个对象的方法和属性。在 中Object Browser,您可以在 中选择一个类,Classes box并在框中选择一个方法或属性Members

于 2022-01-15T13:00:16.513 回答
0

所以问题特别是 appXL.Cells.Find 函数中的“After:=Range”部分。我忘记了这一点,因为我使用的是 word doc 而不是 excel,所以我需要指定 appXL.Range 而不仅仅是 Range。哦,发现我为期一周的问题的喜悦只是一个简单的缺课规范。

也就是说,感谢@Eugene 通知我对象浏览器窗口。那很有用。

于 2022-01-20T22:43:02.877 回答
0

appXL 是一个 excel.Application 对象。Worksheets 属性属于 Workbook 类。您可以只使用 Worksheets.(...) 来引用活动的工作簿工作表。与属性 .Cells 相同

或者您可以定义一个新的 Workbook 变量并处理它:

Dim wbXL as Workbook
set wbXL = ActiveWorkbook
wbXL.Worksheets(...).Activate
于 2022-01-13T20:51:15.047 回答