2013-02-09 76 views
0

我想运行此代码的VB代码,但它给了我下面提到的错误。在文件夹中的所有xls文件上运行Excel宏

任何帮助将不胜感激,因为我是新来的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 = 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 

命令:cscript C:\宏\ test.vbs

结果:错误,2号线,38字符,预计 ')'

回答

1

你的错误是因为你设置Foldername As String但你不需要“作为字符串”。但是,您的代码中存在更多错误。 VBScript不能像Visual Basic或Excel中的宏一样工作。您需要实际调用函数/子例程来执行某些操作。在你的代码中某处(你的子程序之外),你必须Call test

接下来,Dir()函数在VBScript中不可用,所以你必须使用不同的东西。可比较的东西是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

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 

Excel工作簿现在修改电子表格将是你下一个任务。这应该让你朝正确的方向发展。希望有所帮助。

相关问题