我在word文档中有一个标签格式,如下所示
<Name_Prod1>
<Curr_Cost1>
<Est_Cost1>
<Name_Prod11>
<Curr_Cost11>
<Est_Cost11>
<<Name_Prod12>
<Curr_Cost12>
<Est_Cost12>
<Name_Prod13>
<Curr_Cost13>
<Est_Cost13>
以此类推。
我的excel格式如下:
<S.NO> <Product name> <Current cost> <Est cost>
我想通过excel工作表获得值,并在相关标签的标题中替换它们。
我的代码如下。但是我不能创建一种通用的格式来将编号附加到标签名称,并循环通过标签编号。
Private Sub CommandButton1_Click()
Dim objExcel As New Excel.Application
Dim exWb As Excel.Workbook
Set exWb = objExcel.Workbooks.Open("C:****.xlsx")
Dim i As Integer
Dim j As Integer: j = 1
'For the first set
ThisDocument.Name_Prod1.Caption = exWb.Sheets("Main Sheet").Cells(2, 2)
ThisDocument.Curr_Cost1.Caption = exWb.Sheets("Main Sheet").Cells(2, 3)
ThisDocument.Est_Cost1.Caption = exWb.Sheets("Main Sheet").Cells(2, 4)
'For the next set onwards
For i = 1 To i + 2 = 60
Dim ji As String
ji = j & i
'ji should be 11, 12, 13... as i increases
Dim np As Object: Set np = "Name_Prod" & ji
Dim cc As String: cc = "Curr_Cost" & ji
Dim ec As String: ec = "Est_Cost" & ji
ThisDocument.np.Caption = exWb.Sheets("Main Sheet").Cells(i + 2, 2)
ThisDocument.cc.Caption = exWb.Sheets("Main Sheet").Cells(i + 2, 3)
ThisDocument.ec.Caption = exWb.Sheets("Main Sheet").Cells(i + 2, 4)
Next
exWb.Close
Set exWb = Nothing
End Sub
请提供一些解决方案
发布于 2018-06-06 06:10:57
如果语法正确,并且可以正确地编译此行
ThisDocument.Name_Prod1.Caption = exWb.Sheets("Main Sheet").Cells(2, 2)
然后,您应该能够使用相同的方法引用其他标签。只需将变量插入带括号的ThisDocument值即可
ThisDocument.np.Caption
成为ThisDocument(np).Caption
ThisDocument.cc.Caption
成为ThisDocument(cc).Caption
ThisDocument.ec.Caption
成为ThisDocument(ec).Caption
用Option Explicit
启动你的模块总是一个好主意--然后当你使用Debug | Compile
时,你可以报告导致错误消息的那一行,并将错误消息添加到你的问题中。这些是写出一个有机会得到回答的好问题的关键。
https://stackoverflow.com/questions/50709097
复制相似问题