我正在使用一个多维数组来保存几列数据的宏。然后,宏将数组值放在新的工作簿中。一切正常,除了一个if语句。这是带有if语句的子例程
Sub push(toWorkbook As Workbook, ByRef code() As Variant)
'activeBook = "TempEDI.xlsm"
'Workbooks(activeBook).Activate 'set new workbook as active book
Dim newSheet As Worksheet
Set newSheet = toWorkbook.Sheets(1)
h = 2
f = 0
g = 0
newSheet.Cells(1, 1).Value = "Customer"
newSheet.Cells(1, 2).Value = "Invoice #"
newSheet.Cells(1, 6).Value = "ASN"
For i = 0 To UBound(code)
newSheet.Cells(h, 1).Value = code(i, 0)
newSheet.Cells(h, 2).Value = code(i, 1)
If code(f, 2) = code(i, 1) Then
newSheet.Cells(h, 6).Value = code(f, 2)
f = f + 1
End If
If code(g, 3) = code(i, 1) Then '****** <--- THIS IS THE STATEMENT
newSheet.Cells(h, 3).Value = code(g, 3)
newSheet.Cells(h, 4).Value = code(g, 4)
newSheet.Cells(h, 5).Value = code(g, 5)
g = g + 1
End If
h = h + 1
Next i
MsgBox code(g, 3) & " " & code(g, 1)
End Sub
看,我的第一个if语句可以正常工作,但是第二个永远不会求值为true,即使我知道code(0,3)= code(0,1)也是这样。我什至在子例程的末尾放置了一个MsgBox来吐出两个值,并且它们是相同的。知道发生了什么吗?为什么此陈述永远不会评估为真?任何帮助,想法或指针表示赞赏。预先感谢。
答案 0 :(得分:0)
如果DataHelper
是二维的,请尝试:
code()
可能还有其他问题。
答案 1 :(得分:0)
如@ cybernetic.nomad所述 代码(0,3)中有空格。解决方案就像@dwirony所说的那样使用trim函数
If Trim(code(g, 3)) = Trim(code(i, 1)).
为了让您高枕无忧,我建议对所有涉及到存在未知空白风险的数据进行修整。
在此处使用trim更新了代码:
Sub push(toWorkbook As Workbook, ByRef code() As Variant)
'activeBook = "TempEDI.xlsm"
'Workbooks(activeBook).Activate 'set new workbook as active book
Dim newSheet As Worksheet
Set newSheet = toWorkbook.Sheets(1)
h = 2
f = 0
g = 0
newSheet.Cells(1, 1).Value = "Customer"
newSheet.Cells(1, 2).Value = "Invoice #"
newSheet.Cells(1, 6).Value = "ASN"
For i = 0 To UBound(code)
newSheet.Cells(h, 1).Value = code(i, 0)
newSheet.Cells(h, 2).Value = code(i, 1)
If code(f, 2) = code(i, 1) Then
newSheet.Cells(h, 6).Value = code(f, 2)
f = f + 1
End If
If Trim(code(g, 3)) = Trim(code(i, 1)) Then '****** <--- THIS IS THE STATEMENT
newSheet.Cells(h, 3).Value = code(g, 3)
newSheet.Cells(h, 4).Value = code(g, 4)
newSheet.Cells(h, 5).Value = code(g, 5)
g = g + 1
End If
h = h + 1
Next i
MsgBox code(g, 3) & " " & code(g, 1)
End Sub