[Yêu cầu code]Vlookup từ Table_array là file txt (1 người xem)

Liên hệ QC

Người dùng đang xem chủ đề này

hochoaivandot

Thành viên mới
Tham gia
13/2/09
Bài viết
22
Được thích
0
GPE viết giúp mình code VBA, mục đích tạo hàm tự lập với các nội dung sau:
- Tên hàm: vlookuptxt
- Công dụng: Hoàn toàn giống hàm vlookup có sẵn của Excel, nhưng Table_array là 1 file txt
- Cú pháp hàm vloouptxt (lookup_value,txt_array,col_index_num,range_lookup)

Mình gởi file đính kém.

Xin cảm ơn GPE.
 

File đính kèm

GPE viết giúp mình code VBA, mục đích tạo hàm tự lập với các nội dung sau:
- Tên hàm: vlookuptxt
- Công dụng: Hoàn toàn giống hàm vlookup có sẵn của Excel, nhưng Table_array là 1 file txt
- Cú pháp hàm vloouptxt (lookup_value,txt_array,col_index_num,range_lookup)

Mình gởi file đính kém.

Xin cảm ơn GPE.

Cần có 2 code
1> Sub hổ trợ
Mã:
Public sArray
Private Sub GetValFromTxt(ByVal txtFile As String)
  Dim tmpArr
  On Error Resume Next
  If InStr(txtFile, "\") = 0 Then txtFile = ThisWorkbook.Path & "\" & txtFile
  With CreateObject("Scripting.FileSystemObject")
    If .FileExists(txtFile) Then
      With .OpenTextFile(txtFile, 1, , -2)
        tmpArr = Split(.ReadAll, vbCrLf)
        If IsArray(tmpArr) Then sArray = tmpArr
        .Close
      End With
    End If
  End With
End Sub
2> Hàm chính:
Mã:
Function Vlookuptxt(ByVal lookup_Value, ByVal txtFile As String, ByVal ColIndex As Long)
  Dim Arr, Item, tmp
  On Error Resume Next
  Vlookuptxt = vbNullString
  If InStr(txtFile, "\") = 0 Then txtFile = ThisWorkbook.Path & "\" & txtFile
  If CreateObject("Scripting.FileSystemObject").FileExists(txtFile) Then
    If Not IsArray(sArray) Then GetValFromTxt txtFile
      If IsArray(sArray) Then
      For Each Item In sArray
        If InStr(CStr(Item), vbTab) Then
          tmp = Split(Item, vbTab)
          If CStr(tmp(0)) Like lookup_Value Then
            Vlookuptxt = tmp(ColIndex - 1)
            Exit Function
          End If
        End If
      Next
    End If
  End If
End Function
Lưu ý:
- Nếu file txt chứa chuổi là tiếng Việt Unicode thì phải lưu ở dạng Unicode (hoặc UTF_8)
- Hàm hổ trợ dò tìm thông qua ký tự đại diện. Ví dụ có thể gõ công thức:
Mã:
=vlookuptxt([COLOR=#ff0000]"Nguyễn *"[/COLOR],"C:\Users\Anh Tuan\Desktop\GPE\data.txt",2)
Mã:
=vlookuptxt([COLOR=#ff0000]"*J"[/COLOR],"C:\Users\Anh Tuan\Desktop\GPE\data.txt",2)
- Không cần phải gõ đường dẫn đầy đủ cho file TXT. Nếu chỉ ghi tên file không có tên thư mục thì mặc định là nói đến file TXT nằm cùng thư mục với thư mục chứa file Excel hiện hành. Ví dụ
Mã:
=vlookuptxt($B2,[COLOR=#ff0000]"data.txt"[/COLOR],2)
 

File đính kèm

Upvote 0
Web KT

Bài viết mới nhất

Back
Top Bottom