我的问题是,我需要打开一些excel文件使用VBA (对于excel 2007)并提取数据。我想打开的所有文件都被称为“January.xlsx的利润”、“February.xlsx的利润”等等,只是更改了月份名称,所以我想打开一个名为“利润为*”的文件。文件夹中还有一个名为“完全revenue.xlsx”的文件,我不想打开它。
如果可能的话,我需要代码从文件夹中的文件中提取数据,无论文件夹在哪里,因为我将此代码发送给我的同事,将其放入自己的文件夹中,文件夹具有相同的文件名格式等,但路径不同。
我有提取数据的代码,它可以工作,但它要么导入文件夹中的所有数据,要么一点也不导入!
在这方面的任何帮助都将是非常感谢,因为我是一个实习生试图让他的脚,这将是一个相当大的突破对我!
进一步信息
到目前为止,我有下面的代码(我没有包括dim的,因为我觉得它们可能是不必要的?),这是我从其他网站提取的。我还发现,在尝试打开文件夹中的所有文件时,它试图打开自己!如果有人能建议如何改进这一点,我将不胜感激。我没有很长时间使用VBA,而且一直觉得这个任务很难完成!
有时出现的错误框表示,我需要一个变量sfilename的“object”,而且我不知道如何做到这一点,而不需要搞乱代码的另一部分。
sub import data ()
ChDir ThisWorkbook.Path
Set objFSO = CreateObject("Scripting.FileSystemObject")
Set sfolder = objFSO.GetFolder(ThisWorkbook.Path)
For Each sfilename In sfolder.Files
If sfilename <> "Total Revenue.xlsx" Then
Workbooks.Open Filename:= _
sfilename *'open the file*
Set sfilename = ActiveWorkbook *'set the file name as sfilename, so the single piece of code will work with the copy-loop*
b = Sheets.Count *'for the data-import loop*
Call ImportData *'call in the loop*
sfilename.Close *'close the file*
End If
Next
end sub发布于 2011-01-14 11:21:58
你现在用的是什么?对于文件夹中的每个文件?
可能包括
月名(I)
编辑
Sub import_data()
sPath = ThisWorkbook.Path
sTemplate = "\profit for qqq.xls"
For i = 1 To 12
sFileName = Replace(sTemplate, "qqq", MonthName(i))
''Just checking
If Dir(sPath & sFileName) <> "" Then
Workbooks.Open Filename:= _
sPath & sFileName
'open the file*
Set sFileName = ActiveWorkbook
'set the file name as sfilename, so the single
'piece of code will work with the copy-loop*
b = Sheets.Count
'*'for the data-import loop*
''Call ImportData
'*'call in the loop*
sFileName.Close
'*'close the file*
End If
Next
End Sub发布于 2011-01-14 16:03:05
到目前为止,我有下面的代码(我没有包括dim的,因为我觉得它们可能是不必要的?),这是我从其他网站提取的。我还发现,在尝试打开文件夹中的所有文件时,它试图打开自己!如果有人能建议如何改进这一点,我将不胜感激。我没有很长时间使用VBA,而且一直觉得这个任务很难完成!
有时出现的错误框表示,我需要一个变量sfilename的“object”,而且我不知道如何做到这一点,而不需要搞乱代码的另一部分。
非常感谢和亲切的问候,马克
子导入数据()
ChDir ThisWorkbook.Path
Set objFSO = CreateObject("Scripting.FileSystemObject")
Set sfolder = objFSO.GetFolder(ThisWorkbook.Path)
For Each sfilename In sfolder.Files
If sfilename <> "Total Revenue.xlsx" Then
Workbooks.Open Filename:= _
sfilename *'open the file*
Set sfilename = ActiveWorkbook *'set the file name as sfilename, so the single piece of code will work with the copy-loop*
b = Sheets.Count *'for the data-import loop*
Call ImportData *'call in the loop*
sfilename.Close *'close the file*
End If
Next端子
https://stackoverflow.com/questions/4690107
复制相似问题