简体   繁体   中英

Search all columns in an excel column and check value against file name in folder to see if exists?

I have a folder with .txt files:

\\uksh000-file06\SharedAreas\1.0 Hewden Public\NS\Approval

Each text file has a random name like so:

NS123SHS.txt
NSg234eH.txt
NSds3461.txt

Most of the files file names (minus the extenstion .txt) are in my excel sheet in column c.

NS123SHS
NSds3461

I am trying to scan column c to check if the filename is found in my folder directory and if yes show a message saying found, else show a message saying not found.

So far all I've been able to figure out is how to scan my column for specific value, which i define, however I want to be able to scan the entire column, and compare each value to see if it exists in my folder?

Can someone please show me how I might do this please? Thanks

Private Sub Workbook_Open()

Dim FindString As String
Dim Rng As Range
FindString = "NSds3461"
If Trim(FindString) <> "" Then
    With Sheets("Home").Range("C:C") 'searches all of column A
        Set Rng = .Find(What:=FindString, _
                        After:=.Cells(.Cells.Count), _
                        LookIn:=xlValues, _
                        LookAt:=xlWhole, _
                        SearchOrder:=xlByRows, _
                        SearchDirection:=xlNext, _
                        MatchCase:=False)
        If Not Rng Is Nothing Then
             MsgBox "found" 'value not found
        Else
            MsgBox "Reference Not Found" 'value not found
        End If
    End With

End If

In the code bellow you'll have to update Worksheets( 1 ) to the sheet index where you have the file names, and FOLDER_PATH with your info:

\\\\uksh000-file06\\SharedAreas\\1.0 Hewden Public\\NS\\Approval

.

Option Explicit

Private Sub Workbook_Open()

    Const FOLDER_PATH   As String = "C:\temp\"
    Const FILE_NAME_COL As Long = 3

    Dim fileNames As Variant, ws As Worksheet, i As Long
    Dim fName As String, result As String

    Set ws = Worksheets(1)

    fileNames = ws.UsedRange.Columns(FILE_NAME_COL)

    For i = 2 To UBound(fileNames)

        fName = Trim(fileNames(i, 1))

        If Len(Dir(FOLDER_PATH & fName)) > 0 Then
            fName = fName & vbTab & ": Found" & vbCrLf
        Else
            fName = fName & vbTab & ": Not Found" & vbCrLf
        End If

        result = result & i - 1 & ". " & vbTab & fName
    Next

    MsgBox result, , "Search Result"

End Sub

.

Result:

在此处输入图片说明

Hope it helps

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM