两个串联字符串的可怕类型不匹配 - 为什么?

时间:2014-09-18 05:40:54

标签: excel-vba vba excel

此代码有效:

Dim tline1 As Variant
tline1 = EIRPCases.Range(EIRPCases.Cells(CaseStart + 1 + (i - 1) * CaseRowNum, 4),EIRPCases.Cells(32 + (i - 1) * CaseRowNum, 4)).Value
[EB_WGType].Value = tline1

也就是说,它将tline1的字符串复制到名为EB_WGType

的单元格中

但是以下内容会返回类型不匹配错误:

Dim tline1 As Variant, tline2 As Variant
tline1 = EIRPCases.Range(EIRPCases.Cells(CaseStart + 1 + (i - 1) * CaseRowNum, 4),EIRPCases.Cells(32 + (i - 1) * CaseRowNum, 4)).Value
tline2 = EIRPCases.Range(EIRPCases.Cells(CaseStart + 1 + (i - 1) * CaseRowNum, 5),EIRPCases.Cells(32 + (i - 1) * CaseRowNum, 5)).Value
[EB_WGType].Value = tline1 & tline2

我只想连接tline1和tline2字符串并将它们复制到命名单元格EB_WGType中。有什么问题?

1 个答案:

答案 0 :(得分:2)

tline1tline2定义为Variant,从最有可能跨越多个单元格的范围接收其值,它们实际上是数组。 &运算符不知道如何连接它们。

您可以尝试For...Next循环来手动构建tline1tline2的字符串表示形式,然后将它们连接起来。 E.g。

Dim tline1 As Variant, tline2 As Variant, c As Variant
Dim sTmptline1 As String, sTmptline2 As String

tline1 = EIRPCases.Range(EIRPCases...
tline2 = EIRPCases.Range(EIRPCases...

For Each c In tline1
    sTmptline1 = sTmptline1 & CStr(c)
Next
For Each c In tline2
    sTmptline2 = sTmptline1 & CStr(c)
Next
[EB_WGType].Value = sTmptline1 & sTmptline2

然而,当您在构建字符串的数组中进行迭代时,您可能只需将两个数组都用于sTmptline。 E.g。

Dim tline1 As Variant, tline2 As Variant, c As Variant
Dim sTmptline As String

tline1 = EIRPCases.Range(EIRPCases...
tline2 = EIRPCases.Range(EIRPCases...

For Each c In tline1
    sTmptline = sTmptline & CStr(c)
Next
For Each c In tline2
    sTmptline = sTmptline & CStr(c)
Next
[EB_WGType].Value = sTmptline

请注意,直接从范围创建的数组是二维数组(即使它们只包含来自一行或一列的数据),因此您无法在不首先将它们转换为Join函数的情况下使用它一维数组。