对文件夹中的所有xls文件运行Excel宏
我试图运行这个代码的VB代码,但它给我的错误,这是下面提到的 任何帮助都将不胜感激,因为我是VB新手对文件夹中的所有xls文件运行Excel宏,excel,vbscript,vba,Excel,Vbscript,Vba,我试图运行这个代码的VB代码,但它给我的错误,这是下面提到的 任何帮助都将不胜感激,因为我是VB新手 **Code :** Option Explicit Public Sub ReadExcelFiles(FolderName As String) Dim FileName As String ' Add trailing \ character if necessary ' If Right(FolderName, 1) <> "\" Then FolderName = Fo
**Code :**
Option Explicit
Public Sub ReadExcelFiles(FolderName As String)
Dim FileName As String
' Add trailing \ character if necessary
'
If Right(FolderName, 1) <> "\" Then FolderName = FolderName & "\"
FileName = Dir(FolderName & "*.xls")
Do While FileName <> ""
Workbooks.Open (FolderName & FileName)
Sub Macro1()
'
' Macro1 Macro
'
'
Range("A1").Select
ActiveCell.FormulaR1C1 = "Name"
Range("B1").Select
ActiveCell.FormulaR1C1 = "Anil"
Range("A2").Select
End Sub
Workbooks(FileName).Close
FileName = Dir()
Loop
End Sub
Public Sub test()
ReadExcelFiles ("C:\Macro")
End Sub
**代码:**
选项显式
公共子ReadExcelFiles(FolderName为字符串)
将文件名设置为字符串
'必要时添加尾随\字符
'
如果正确(FolderName,1)“\”则FolderName=FolderName&“\”
FileName=Dir(FolderName&“*.xls”)
文件名“”时执行此操作
工作簿.打开(文件夹名和文件名)
亚宏观1()
'
'宏1宏
'
'
范围(“A1”)。选择
ActiveCell.FormulaR1C1=“名称”
范围(“B1”)。选择
ActiveCell.FormulaR1C1=“Anil”
范围(“A2”)。选择
端接头
工作簿(文件名)。关闭
FileName=Dir()
环
端接头
公共子测试()
ReadExcelFiles(“C:\Macro”)
端接头
命令:cscript c:\macro\test.vbs
结果:错误,第2行,字符38,预期'”您的错误是因为您将
Foldername设置为字符串,但不需要“作为字符串”。但是,代码中还有更多错误。VBScript的工作方式与Visual Basic或Excel中的宏不同。您需要实际调用函数/子例程以执行某些操作。在代码中的某个地方(子例程之外),必须调用test
接下来,VBScript中没有Dir()函数,因此必须使用不同的函数。非常类似的是Dim fso:set fso=CreateObject(“Scripting.FileSystemObject”)
然后使用fso.FIleExists(FileName)
接下来,您不能像在宏中那样访问Excel工作簿。您不能使用Workbooks.Open(FolderName&FileName)
。您可以使用Dim-xl:set-xl=CreateObject(“Excel.application”)
然后使用xl.application.Workbooks.Open FileName
以下是我的代码,用于仅从vbscript打开excel工作簿
Option Explicit
Call test
Sub ReadExcelFiles(FolderName)
Dim FileName
Dim fso: set fso = CreateObject("Scripting.FileSystemObject")
Dim xl: set xl = CreateObject("Excel.application")
If Right(FolderName, 1) <> "\" Then FolderName = FolderName & "\"
FileName = (FolderName & "test" & ".xls")
If (fso.FIleExists(FileName)) Then
xl.Application.Workbooks.Open FileName
xl.Application.Visible = True
End If
End Sub
Sub test()
ReadExcelFiles ("C:\Users\Developer\Desktop\")
End Sub
选项显式
呼叫测试
子ReadExcelFiles(FolderName)
暗文件名
Dim fso:set fso=CreateObject(“Scripting.FileSystemObject”)
Dim xl:set xl=CreateObject(“Excel.application”)
如果正确(FolderName,1)“\”则FolderName=FolderName&“\”
文件名=(文件夹名和“测试”和“.xls”)
如果(fso.FIleExists(FileName)),则
xl.Application.Workbooks.Open文件名
xl.Application.Visible=True
如果结束
端接头
子测试()
ReadExcelFiles(“C:\Users\Developer\Desktop\”)
端接头
现在,修改电子表格将是您的下一项任务。这会让你走上正确的方向。希望有帮助