[英]Excel/VBA - For Each Loop and StringComp
我正在尝试从外部/封闭的excel工作表中获取列,并将其与工作表中的列进行比较。
问题是,对于我的一些输入,结果是假的,因为比较不正确,所以程序告诉我,我的数组found()不足以容纳所有数据
我的代码:
Private Sub CommandButton1_Click()
Dim varData As Variant
Dim objExcel As New Excel.Application
Dim objSheet As Object
Dim extRange As Variant
Dim intRange As Variant
Set intRange = ThisWorkbook.Sheets(1).Range("A4:A11")
Dim loopStr As Variant
Dim loopStr2 As Variant
Dim found() As Variant
Dim loopInt As Integer
Dim endStr As Variant
loopInt = 1
varData = Application.GetOpenFilename("Excel (*.xlsx), *.xlsx")
If varData <> False Then
objExcel.Workbooks.Open varDatei
Set objSheets = objExcel.Sheets(1)
objSheets.Activate
LastRow = objSheets.Cells(Rows.Count, 3).End(xlUp).Row
Set extRange = objSheets.Range("B3:B" & LastRow)
ReDim found(1 To LastRow)
For Each loopStr In extRange
For Each loopStr2 In intRange
If StrComp(loopStr, loopStr2) = True Then
found(loopInt) = loopStr
loopInt = loopInt + 1
End If
Next loopStr2
Next loopStr
loopStr = ""
For Each loopStr In found
endStr = endStr + " " + loopStr
Next loopStr
Debug.Print endStr
Else
MsgBox "Error"
End If
End Sub
LastRow = objSheets.Cells(Rows.Count,3).End(xlUp).Row
“行”在我看来似乎是不确定的。 通常的语法是
LastRow = objSheets.Cells(objSheets.Rows.Count, 3).End(xlUp).Row
(或您要为其计算行的任何工作表)或
LastRow = objSheets.Cells(.Rows.Count, 3).End(xlUp).Row
对于当前工作表。 检查调试器关于“ Rows.Count”的内容。 尝试此操作,如果发现有用,请回复。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.