我需要从CSV文件中提取数据到现有的Excel文件中。我对自定义函数和Excel的整体机制知之甚少,因此在GPT 3.5的帮助下,我开发了一个自定义函数,用于从具有2条记录的测试csv文件中提取数据。
下面是GPT给我的函数:
Function GetCSVCellValueFromRecord(csvFilePath As String, recordIndex As Long, targetColumnName As String) As Variant
Dim csvContent As String
Dim lines() As String
Dim headers() As String
Dim columnIndex As Long
Dim i As Long
' Read the entire CSV file into a string
Open csvFilePath For Input As #1
csvContent = Input$(LOF(1), 1)
Close #1
' Split the CSV content into lines
lines = Split(csvContent, vbCrLf)
' Get the headers from the first line
headers = Split(lines(0), ",")
' Find the column index of the target data
columnIndex = -1
For i = LBound(headers) To UBound(headers)
If Trim(headers(i)) = targetColumnName Then
columnIndex = i
Exit For
End If
Next i
' Return an error if the column name is not found
If columnIndex = -1 Then
GetCSVCellValueFromRecord = CVErr(xlErrValue)
Exit Function
End If
' Check if the requested record index is within bounds
If recordIndex >= 1 And recordIndex <= UBound(lines) Then
Dim fields() As String
fields = Split(lines(recordIndex), ",")
If UBound(fields) >= columnIndex Then
GetCSVCellValueFromRecord = Trim(fields(columnIndex))
Exit Function
End If
End If
' Return an error if the record or data is not found
GetCSVCellValueFromRecord = CVErr(xlErrValue)
End Function
我尝试的函数调用是:=GetCSVCellValueFromRecord(“potter.csv”,1,“time”)(csv与工作表在同一个文件夹中)=GetCSVCellValueFromRecord(Potter. csv,2,comment)都返回了一个#Value!错误。我不确定出了什么问题,或者从这里去哪里
我的最终目标是能够将csv文件名输入到一个字段中,并使函数调用引用该单元格,以便用csv中的信息更新所有相关字段。
1条答案
按热度按时间ebdffaop1#
如果问题是你需要完整的路径,但只想传递文件名,那么这个改变
...只要所有CSV文件都位于保存具有UDF的工作簿的同一文件夹中,就可以执行您想要的操作。