【发布时间】:2018-06-05 21:20:03
【问题描述】:
我在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
请帮忙解决一下
【问题讨论】:
-
这项工作是否有效
ThisDocument.Name_Prod1.Caption = exWb.Sheets("Main Sheet").Cells(2, 2)- 您是否收到错误消息或格式不正确的字符串?示例非常适合调试 -
是的,第一组有效
-
尝试将变量名放在数组样式中 - 查看答案