循环浏览文件夹中的每个工作簿+按下按钮VBA

时间:2016-09-29 01:14:43

标签: excel excel-vba button vba

Sub LoopAllExcelFilesInFolder()

Dim wb As Workbook
Dim myPath As String
Dim myFile As String
Dim myExtension As String
Dim FldrPicker As FileDialog

'Optimize Macro Speed
  Application.ScreenUpdating = False
  Application.EnableEvents = False
  Application.Calculation = xlCalculationManual

'Retrieve Target Folder Path From User
  Set FldrPicker = Application.FileDialog(msoFileDialogFolderPicker)

    With FldrPicker
      .Title = "Select A Target Folder"
      .AllowMultiSelect = False
        If .Show <> -1 Then GoTo NextCode
        myPath = .SelectedItems(1) & "\"
    End With

'In Case of Cancel
NextCode:
  myPath = myPath
  If myPath = "" Then GoTo ResetSettings

'Target File Extension (must include wildcard "*")
  myExtension = "*.xls"

'Target Path with Ending Extention
  myFile = Dir(myPath & myExtension)

'Loop through each Excel file in folder
  Do While myFile <> ""
    'Set variable equal to opened workbook
      Set wb = Workbooks.Open(Filename:=myPath & myFile)

    'Ensure Workbook has opened before moving on to next line of code
      DoEvents

    'Press button in sheet 51
      wb.Worksheets("51").CommandButton1.Value = True

    'Save and Close Workbook
      'wb.Close SaveChanges:=True

    'Ensure Workbook has closed before moving on to next line of code
      DoEvents

    'Get next file name
      myFile = Dir
  Loop

'Message Box when tasks are completed
  MsgBox "Task Complete!"

ResetSettings:
  'Reset Macro Optimization Settings
    Application.EnableEvents = True
    Application.Calculation = xlCalculationAutomatic
    Application.ScreenUpdating = True

End Sub

我有一个包含50个工作簿的文件夹,每个工作簿中都有相同的工作表。我在工作簿中的每个工作表中都有2个按钮,允许我下载/上传到db。我需要遍历每个工作簿并按下sheet51中的上传按钮。

wb.Worksheets(“51”)。CommandButton1.Value = True

任何人都可以看看我做错了什么吗?我收到此消息 - 运行时错误:'438':对象不支持此属性或方法。

1 个答案:

答案 0 :(得分:1)

CommandButtons没有Value属性,所以我想你想调用按钮的Click事件,即:

wb.Worksheets("51").CommandButton1_Click

CommandButton1_Click事件首先需要声明Public,而不是Private,即:

Public Sub CommandButton1_Click()

虽然它被声明为Private,但它只能通过工作表本身的代码访问。

以下编辑,我非常感谢,是由共产国际制作的:

注意:如果您不想手动更改所有事件处理程序例程,可以使用VBA Extensibility将它们从Private更改为Public:

'Requires a reference to Microsoft Visual Basic for Applications Extensibility
'Also requires "Trust access to the VBA project object model" to be checked.
'in Macro Security.

Dim targetLine As Long

'The "51" in VBComponents("51") is the name of the code module which is usually, but
'not always, the same as the sheet name
With wb.VBProject.VBComponents("51").CodeModule
    targetLine = .ProcStartLine("CommandButton1_Click", vbext_pk_Proc)
    .ReplaceLine targetLine, "Public Sub CommandButton1_Click()"
End With

wb.Sheets("51").CommandButton1_Click
相关问题