2013-04-05 80 views
0

要保持簡單:我需要將一個Excel工作簿中的userID號碼與另一個Excel工作簿中的號碼相匹配。這個想法是看這兩個文件中較大的文件是否來自較小文件的這個userID號碼。如果較大的文檔有userID號碼,其他數據需要複製到較小的文檔(我知道如何做到這一點)如何比較不同工作簿中的兩個字符串(Excel VBA)

我的問題是,當我比較每個字段,我的功能不斷顯示我的searchString(大文檔中的字符串)爲空白。它不是在我創建的數組上創建的,而是像我在小文檔中創建的數組一樣。代碼將會比我更好地解釋。我不是程序員,也不是真的瞭解VBA,所以我已經知道我的代碼是不合格的。

每當我測試我的代碼,我有MsgBox函數讓我看看它比較的字符串,出於某種原因,「searchString」總是顯示爲空白,所以它比較我的「findString」它有它需要的數據,無論出於何種原因都可以爲空白字符串我需要MsgBox函數來顯示來自其他文檔的數組數據,而不僅僅是一個空白框。

'NID Comparisson Script 

Sub getUID() 

'Select Appropriate cell 
Range("C2").Select 

'Count the number of rows that contain data in the SCCM document. 
Dim rows As Integer 
rows = ActiveSheet.UsedRange.rows.count 

'Create Array 
With Sheets("SMSReportResults(2)") 
    arrData = .Range(.Cells(2, 3), .Cells(rows, 3)).Value 
End With 

'Declare a variable for comparing UID/NID strings 
Dim findString As String 

'Loop through the document and grab the UID numbers as "searchString" 
For i = 1 To rows - 1 
    findString = arrData(i, 1) 
    Windows("NIDs.xlsx").Activate 
    Dim rows2 As Integer 
    rows2 = ActiveSheet.UsedRange.rows.count 

    'Create second array in the NIDs Workbook 
    With Sheets("Sheet1") 
     arrData2 = .Range(.Cells(2, 1), .Cells(rows, 1)).Value 
    End With 

    'Create searchString for NIDs workbook 
    Dim searchString As String 

    For j = 1 To rows2 - 1 
     searchString = arrData2(j, 1) 

     Dim compare As Integer 
     compare = StrComp(searchString, findString) 
     MsgBox (seachString) 
     MsgBox (findString) 
     MsgBox (compare) 
     ActiveCell.Offset(1, 0).Select 

    Next 
Next 

End Sub 
+0

您可以編寫代碼,這可是這真的是什麼VLOOKUPS適用於 – 2013-04-05 21:47:16

回答

1

轉到模塊頂部並輸入「Option Explicit」。你在「MsgBox(seachString)」裏拼錯了searchString,因此創建了一個新的變量。

0

有可能是這樣做的更有效的方法,有什麼用嵌套循環,但是這基本上是我認爲你需要做的:

Dim rows  As Integer 
Dim arrData  As Variant 
Dim arrData2 As Variant 

rows = ThisWorkbook.ActiveSheet.UsedRange.rows.Count 

With Sheets("SMSReportResults(2)") 
    arrData = .Range(.Cells(2, 3), .Cells(rows, 3)).Value 
End With 

On Error Resume Next 
    Windows("NIDs.xlsx").Activate 
On Error GoTo 0 

With Workbooks("NIDS.xlsx").Sheets("Sheet1") 
    arrData2 = .Range(.Cells(2, 1), .Cells(rows, 1)).Value 
End With 

For R1 = 1 To UBound(arrData, 1) 
    For C1 = 1 To UBound(arrData, 2) 
     For R2 = 1 To UBound(arrData2, 1) 
      For C2 = 1 To UBound(arrData2, 2) 
       If arrData(R1, C1) = arrData2(R2, C2) Then 

        'Returns the value from the next column in NIDS 
        MsgBox Workbooks("NIDS.xlsx").Sheets("Sheet1").Cells(R2, C2 + 1) 

       End If 
      Next C2 
     Next R2 
    Next C1 
Next R1 
相關問題