2014-03-28 77 views
1

返回數組我有一個表如何使用VLOOKUP

date number 
01/14 1324e3 
01/15 134d32 
01/14 15233t 
01/13 1s3634 
01/14 133624 

我需要得到一個String正是這樣'1324e3','15233t','133624',我。即對應的01/14


Public Function getString (myDate As Variant) As String 
Dim ws2 As Worksheet 
Set ws2 = This.Workbook.Worksheets("Sheet1") 

getString = Application.Vlookup(myDate, ws2.Range("A:B"),2,false) 
End Function 

所有時間工作正常,但只返回一個值,我怎麼能糾正呢?

回答

1

看起來您錯誤地從SQL數據庫中提取數據,因爲日期和數字列的格式通常不是標準格式。對於數字列(我不確定應該是字符串還是數字),您可能會遇到像「1234e3」這樣的數字問題,因爲Excel會將其識別爲數字而不是字符串。除非您將其保留爲字符串,否則日期列也將轉換爲格式Date:DD-MMM。忽略這些問題,下面的函數應該建立你的字符串。

此外,Vlookup將只返回一個值,因爲你想返回所有匹配,我使用了一個循環。

Public Function GetString(myDate As Variant) As String 
Dim ws2 As Worksheet 
Dim i As Long, Srow As Long, Erow As Long 
Dim BuildString As String 
Set ws2 = ThisWorkbook.Worksheets("Sheet1") 

Srow = 2 
Erow = ws2.Cells(2, 1).End(xlDown).Row 
BuildString = "" 

For i = Srow To Erow 
    If ws2.Cells(i, 1) = myDate Then 
     If BuildString = "" Then 
      BuildString = "'" & ws2.Cells(i, 2) & "'" 
     Else 
      BuildString = BuildString & ",'" & ws2.Cells(i, 2) & "'" 
     End If 
    End If 
Next i 
GetString = BuildString 
End Function