如何在连接时将变量dim传递给字符串?

问题描述 投票:0回答:1

我试图导出一个具有特定名称的文件(其中名称的不同部分是变量)。到目前为止,前两个字符串没有引起问题。当我执行索引匹配函数并得到一个变量数据类型值时,问题就出现了。我无法将变体类型转换为字符串,以便在后面的代码中使用。下面的片段。

Sub Export_Imgs()

    Dim tempSht as Range
    Dim dataSht as Range
    Dim matCell as Range
    Dim jobNum as Range
    Dim buildDate As String
    Dim buildID As String
    Dim imgFile As String
    Dim matID As Variant
    Dim imgMap As String
    Dim imgPDF As String
    Dim imgJPG As String

    Set tempSht = ThisWorkbook.Sheets("Template")
    Set dataSht = ThisWorkbook.Sheets("Machines & Material")
    Set matCell = tempSht.Range("$E$81")
    Set jobNum = tempSht.Range("$E$12")

    'Define file name variables
    buildDate = Format(Date, "YYYY-MM-DD")
    buildID = Left(jobNum, InStr(jobNum, ".") - 1)
    matID = WorksheetFunction.Index((dataSht.ListObjects("AMmat").ListColumns(4).DataBodyRange), _
        WorksheetFunction.Match(matCell, dataSht.ListObjects("AMmat").ListColumns(1).DataBodyRange, 0))

        imgMap = "C:\Users\Example\Desktop\"
        imgJPG = buildDate & "_" & buildID & "_" & CStr(matID) & ".jpg"
        imgFile = imgMap & imgJPG

End Sub

我在代码底部的imgJPG行得到一个 "类型不匹配 "的错误。我觉得我好像漏掉了一些很简单的东西。任何帮助将是非常感激的。

excel vba string concatenation variant
1个回答
0
投票

我不会使用 Index 在这里,而是类似下面的方法。

With dataSht.ListObjects("AMmat")
    Dim rw
    rw = Application.Match(matCell.Value, .ListColumns(1).DataBodyRange, 0)

    If Not IsError(rw) Then
        matId = .ListColumns(4).DataBodyRange.Cells(rw).Value
    End If   
End With
© www.soinside.com 2019 - 2024. All rights reserved.