我有一个excel文件:
Excel.xls
Code date start end
2301 12/08/1993 08:02 08:17
4221 12/08/1993 09:04 09:25
2312 12/08/1993 10:02 10:28
1284 19/09/1994 11:02 11:21
2312 19/09/1994 15:57 16:20
1284 23/06/1995 17:12 17:35
2312 22/06/1996 13:14 13:32
4221 22/06/1996 15:53 16:13
4221 05/05/1999 08:06 08:22
2418 05/05/1999 08:10 08:33
2301 05/05/1999 09:12 09:37
2301 05/05/1999 09:28 10:28
2301 05/05/1999 13:28 13:38
问题:
问题是从excel文件中提取数据到由Code
行连接的另一个文件?
所需解决方案:
将数据从excel文件导入另一个或工作簿,按行数Code
连接到具有相关数据名称的工作表中,例如在工作表2301
中我只能拥有数据的人excel文件中的这段代码:
Sheet2301
Code date start end
2301 05/05/1999 09:12 09:37
2301 05/05/1999 09:28 10:28
2301 05/05/1999 13:28 13:38
.... ...... .... ....
我是VBA的初学者,所以我花了几天时间找到解决方案以解决问题。
编辑:
实际上我有不同的csv文件,我使用这个VBA代码将它们导入到一个唯一的工作表中:
Option Explicit
Sub ImportCSV()
Dim strSourcePath As String
Dim strDestPath As String
Dim strFile As String
Dim strData As String
Dim x As Variant
Dim Cnt As Long
Dim r As Long
Dim c As Long
Application.ScreenUpdating = False
'Change the path to the source folder accordingly
strSourcePath = "path to csv files\"
If Right(strSourcePath, 1) <> "\" Then strSourcePath = strSourcePath & "\"
'Change the path to the destination folder accordingly
strDestPath = "path to csv files\"
If Right(strDestPath, 1) <> "\" Then strDestPath = strDestPath & "\"
strFile = Dir(strSourcePath & "*.csv")
Do While Len(strFile) > 0
Cnt = Cnt + 1
If Cnt = 1 Then
r = 1
Else
r = Cells(Rows.Count, "A").End(xlUp).Row + 1
End If
Open strSourcePath & strFile For Input As #1
If Cnt > 1 Then
Line Input #1, strData
End If
Do Until EOF(1)
Line Input #1, strData
x = Split(strData, ",")
For c = 0 To UBound(x)
Cells(r, c + 1).Value = Trim(x(c))
Next c
r = r + 1
Loop
Close #1
Name strSourcePath & strFile As strDestPath & strFile
strFile = Dir
Loop
Application.ScreenUpdating = True
If Cnt = 0 Then _
MsgBox "No CSV files were found...", vbExclamation
End Sub
并且代码工作得非常好所以我必须通过不同的当前工作表中的数据(正如我之前解释过的那样)加入这个代码?
答案 0 :(得分:0)
不需要VBA,你可以使用公式。
我认为你的每张纸(&#34; 2301&#34;,&#34; 4221&#34;等)都被称为JUST。另外,我假设你每个都有一个标题行。
在非主工作表中,输入此公式(作为数组,使用 CTRL + SHIFT + ENTER 并向上/向下拖动:
=IFERROR(INDEX(Sheet1!A$2:A$14,SMALL(IF(Sheet1!$A$2:$A$14=INT(RIGHT(CELL("filename",A1),LEN(CELL("filename",A1))-FIND("]",CELL("filename",A1)))),ROW(Sheet1!A$2:A$14)-ROW(Sheet1!A$2)+1),ROWS(Sheet1!A$2:A2))),"")
您可能需要调整范围,但这应该可以解决问题。如果您有任何问题,请告诉我们!
现在,您可以在任何工作表上使用该公式。它会在主页(在我的示例中为Sheet1
)中查找匹配项,然后返回等效信息。
尽管您可能需要VB帮助,但是将此公式添加到每个工作表中。如果您需要帮助,请告诉我。
编辑:但请注意,这需要您已将工作簿保存在某处。除非保存工作簿,否则返回工作表名称的公式部分不起作用。