Excel / VBA - For Each Loop和StringComp

时间:2016-01-19 15:20:30

标签: excel vba excel-vba

我试图从外部/已关闭的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

1 个答案:

答案 0 :(得分:0)

  

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”的说法。 如果您发现它有用,请尝试并回复。