2017-05-30 74 views
1

我是新来的VBScript当前foler名新的Excel文件,但想知道如何自动创建一个新的Excel文件,这些的格式为“[文件夹名称] _Summary.xlsx?我的文件夹中。我得到一个文件被创建,但我不得不硬编码的路径是有办法的文件夹中自动创建新的Excel文件创建包含在Excel中的VBScript

这里是我迄今:

Sub Testing() 

strFileName = "F:\U029\U029_Excel\U029_Excel_Summary.xlsx" 

Set objExcel = CreateObject("Excel.Application") 
objExcel.Visible = True 

Set objWorkbook = objExcel.Workbooks.Add() 
objWorkbook.SaveAs (strFileName) 

objExcel.Quit 

End Sub 

回答

2

确保您的VBS文件被放置在您要创建Excel文件的文件夹内。运行vbs文件后,可以从该文件夹中删除它。使用此代码VBS文件内:

call fn_createExcel() 

Function fn_CreateExcel() 
    Dim objFso, objExcel, objWorkbook 
    Set objFso = CreateObject("Scripting.FileSystemobject") 
    strTemp = objFso.GetAbsolutePathName("") 
    tempArr=Split(strTemp,"\") 
    strFileName= strTemp&"\"&tempArr(ubound(tempArr))&"_Summary.xlsx" 
    Set objExcel = CreateObject("Excel.Application") 
    objExcel.Visible = True 
    Set objWorkbook = objExcel.Workbooks.Add() 
    objWorkbook.SaveAs strFileName 

    objExcel.Quit 
    Set objExcel = Nothing 
    Set objFso = Nothing 
End Function 

编辑2: 创建具有如下VBA代码一个XLSM文件(也见附图的图像)。将此xlsm文件放入要创建excel文件的文件夹内,然后打开并运行该过程。 Excel文件创建后,您可以从该文件夹中删除此xlsm文件。

Function fn_CreateExcel() 
    Dim objExcel, objWorkbook, strFileName, strTemp 
    strTemp = Application.ActiveWorkbook.Path 
    tempArr = Split(strTemp, "\") 
    strFileName = strTemp & "\" & tempArr(UBound(tempArr)) & "_Summary.xlsx" 
    Set objExcel = CreateObject("Excel.Application") 
    objExcel.Visible = True 
    Set objWorkbook = objExcel.Workbooks.Add() 
    objWorkbook.SaveAs strFileName 

    objExcel.Quit 
    Set objExcel = Nothing 
End Function 

您可以按照您的要求进一步修改代码/逻辑。我试过这段代码并且正在工作。 enter image description here

+0

感谢您的解决方案。我怎样才能让这个代码在VBA excel工作表中工作?我将你的代码粘贴到Excel中的VBA项目中,但得到了错误“无效的外部过程”。谢谢! – Joe

+1

@Joe查看更新的答案。 – Gurman

1

你可以给这个VBScript中一试:

Call Create_New_Excel_File() 
'*********************************************************** 
Sub Create_New_Excel_File() 
set fso = CreateObject("Scripting.FileSystemObject") 
Path_Folder = fso.GetParentFolderName(WScript.ScriptFullName) 
Array_Folder_Name = split(Path_Folder,"\") 
Folder_Name = Array_Folder_Name(Ubound(Array_Folder_Name)) 
strFileName = Path_Folder & "\" & Folder_Name & "_Summary.xlsx" 
Set objExcel = CreateObject("Excel.Application") 
objExcel.Visible = True 
Set objWorkbook = objExcel.Workbooks.Add() 
objWorkbook.SaveAs(strFileName) 
objExcel.Quit 
End Sub 
'*********************************************************** 
+0

我得到一个编译错误,“无效的外部程序”。 – Joe

+1

@Joe这VBScript的工作与VBA不 我已经发布前测试,它使用VBScript的作品! – Hackoo