2013-02-13 56 views
0

Excel工作表存在,其Sheet1中列A中的機器名稱列表存在。將文件中的值與Excel中的列進行比較,並更新另一列

存在一個文本文件,其中包含已退役的機器列表。

我需要在同一張工作表(Sheet1)的B列下的Excel工作表中將所有退役的機器標記爲「DECOM」。

這是我到目前爲止。

Sub ImportTextFileContents() 
Dim strg As Variant 
Dim EntireLine As String 

FName = Application.GetOpenFilename("Text Files (*.txt), *.txt", , "Choose File to Import") 

Open FName For Input Access Read As #1 
i = 1 
While Not EOF(1) 
    Line Input #1, EntireLine 
    strg = EntireLine 

    If (Sheets("Sheet1").Range("A").Value = strg) Then 
    Sheets("Sheet1").Range("B" & i).Value = "DECOM" 
    End If 

    i = i + 1 
Wend 
EndMacro: 

On Error GoTo 0 
Application.ScreenUpdating = True 

Close #1 
End Sub 
+0

爲什麼不導入內容該文件的電子表格,然後使用公式(如'countif')?我認爲這更容易。 – 2013-02-13 21:55:29

+0

爲避免將數據導入到電子表格中,或爲了效率的緣故創建臨時電子表格,以後需要將其終止,可能更適合。另外,OP需要使用MATCH功能測試,而不是使用CountIf功能來識別TXT文件中列出的機器。 – 2013-02-13 22:32:00

回答

0

嘗試是這樣的:

Sub ImportTextFileContents() 
Dim strg As Variant 
Dim EntireLine As String 
Dim DecomMachines() as String 
Dim rngExcel as Range 
Dim cell as Range 

FName = Application.GetOpenFilename("Text Files (*.txt), *.txt", , "Choose File to Import") 

Open FName For Input Access Read As #1 

'Create an array to contain the list of Decommissioned machines from the TXT file 

i = 1 
While Not EOF(1) 
    Line Input #1, EntireLine 
    strg = EntireLine 
    ReDim Preserve DecomMachines(0 to i-1) 
    DecomMachines(i-1) = strg 
    i = i + 1 
Wend  

'Set the range variable over which we need to iterate: 
Set rngExcel = Sheets("Sheet1").Range("A1",Range("A1").End(xlDown).Address) '<-- modify as needed 

For each cell in rngExcel  
'Check to see if this cell.value exists in the array we built, above: 
    If Not IsError(Application.Match(Cstr(cell.Value),DecomMachines,False)) Then 
     'if the name exists in the DecomMachines array, then we need to mark it as decommissioned. 
     cell.Offset(0,1).Value = "DECOM" 
    Else: 
     'it doesnot exist in the TXT file, so ignore it 
    End If 
Next  

EndMacro: 

On Error GoTo 0 
Application.ScreenUpdating = True 

Close #1 
End Sub 

這將創建一個包含所有在TXT文件中標識的機器的數組,然後遍歷在A列的單元格範圍,測試以查看如果每個單元格值存在於數組中。如果確實存在,那麼我們知道在B列(cell.Offset(0,1))中將其標記爲已停用,並且如果它不存在,則我們轉到列A中的下一個單元格。

+0

這工作完全像我想要的...有一些小的補充是必要的。謝謝大衛! – user811433 2013-02-13 22:53:09

相關問題