首先,我真的是Excel的罕见用户。而现在,我需要用它“发展”。
所以,基本上,我在工作簿中有这个表单(作为第一张表)。此表单具有文件夹目标(CSV文件所在的文件夹),要搜索的值(例如,单元名称)和按钮。可以根据用户在表单中输入的内容来更改文件夹目的地和要搜索的值。
当用户按下按钮时,宏将运行,CSV中匹配单元的一些特征将显示在工作簿的下一页中。
我想知道如何使用该列来搜索和检索CSV中的值。例如,要搜索所有位于CSV的B列中的值,而需要检索的值分别在C和F中。
那么,任何人都可以帮助我吗?我正在进行我的研究和研究,因为我对这门语言还很新。
这是我到目前为止所做的。当我在单个工作簿上尝试时,我可以获得搜索功能(搜索,复制和粘贴)。但我无法获取打开的文件夹,并循环访问文件。谁可以帮我这个事?任何形式的帮助都将非常感激。
Sub Button1_Click()
Dim LSearchRow As Integer
Dim LCopyToRow As Integer
Dim strPath As String
Dim strFile As String
Dim wbSource As Workbook
Dim wsSource As Worksheet
Dim wsMain As Worksheet
Dim wsDest As Worksheet
Dim filePath
Dim numOfData
Dim unitName
On Error GoTo Err_Execute
Set wsMain = ThisWorkbook.Worksheets(1)
Set wsDest = ThisWorkbook.Worksheets(2) 'Set destination worksheet to paste the matching data
wsDest.Cells.Clear
'filePath = wsMain.Range("B4").Value 'Get the file path
unitName = wsMain.Range("B5").Value 'Get the unit name
'Open the files from the path provided
strPath = "C:\Users\Lenovo\Desktop\DataLog"
strFile = Dir(strPath & "\*.csv")
Do While strFile <> vbNullString
Set wbSource = Workbooks.Open(strPath & "\" & strFile)
Set wsSource = wbSource.Worksheets(1)
noOfData = wsSource.Range("A2:A12").Find("*", , , , xlByRows, xlPrevious).Row - 1
'Set row to start to search and copy data to
LSearchRow = 2
LCopyToRow = 2
While Len(wsSource.Range("B" & CStr(LSearchRow)).Value) > 0
'If value in column B = "unitName", copy entire row to Sheet2
If wsSource.Range("B" & CStr(LSearchRow)).Value = unitName Then
'Copy and paste the matching values into the next sheet
For Count = 2 To noOfData + 1
wsDest.Cells(1, 1).Value = "Unit No"
wsDest.Cells(1, 2).Value = unitName
wsDest.Cells(LCopyToRow, 1).Value = _
wsSource.Cells(LSearchRow, 3).Value
wsDest.Cells(LCopyToRow, 2).Value = _
wsSource.Cells(LSearchRow, 6).Value
Next Count
'Move counter to next row
LCopyToRow = LCopyToRow + 1
'Go back to Sheet1 to continue searching
wsSource.Select
End If
LSearchRow = LSearchRow + 1
Wend
wbSource.Close True
strFile = Dir()
Loop
MsgBox "All matching data has been copied."
Exit Sub
Err_Execute:
MsgBox "An error has occurred."
End Sub