我在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
请帮助解决一些问题
答案 0 :(得分:0)
如果您的语法正确,则可以编译此行而不会出现错误
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
时,您可以报告导致错误消息的行并向您的问题添加错误消息。这些是写一个有可能被回答的好问题的关键。