2015-11-16 37 views
1

在vba中编写代码,将一个excel文件的用户窗体调用到所有其他10个excel文件中,而这些excel文件中没有任何引用。以用户形式打开多个excel文件

据显示在当前输出excel文件而不是在目标文件并显示该错误作为用户窗体已经示出和表示形式模态是不可能

Private Sub Workbook_OnClick() 
    Dim mypath As String 
    Dim file As Workbook 
    Dim wb As Workbook 
    Dim pat As String 
    Application.ScreenUpdating = False 
    ChDrive "C:" 
    ChDir "C:\Users\Administrator\Desktop\John" 
    'john is a folder on the desktop 
    mypath = Range("B1").Value 
    'mypath has the same value as chDir 
    file = Dir(mypath & "\" & "*.xlsx") 
    Set wb = Application.Workbooks.Open(file) 
    If (wb.Click) Then 
     Application.Visible = False 
     userform1.Show 
    End If 
End Sub 

CHDIR提及,因为显示的默认目录与dir()函数是C:\ Users \ Administrator \ Documents \,但保存在桌面的文件夹是C:\ Users \ Administrators \ Desktop \ John

先生,它显示运行时错误 - 91即“对象变量或块变量未设置”并突出显示“file = Dir(mypath &“\” &“* .XLSX”)“

回答

0
Private Sub Workbook_OnClick() 
    Dim mypath As String 
    Dim file As String 
    Dim wb As Workbook 
    Dim pat As String 
    Application.ScreenUpdating = False 
    ChDrive "C:" 
    ChDir "C:\Users\Administrator\Desktop\John" 
    'john is a folder on the desktop 
    mypath = Range("B1").Value 
    'mypath has the same value as chDir 
    file = Dir(mypath & "\" & "*.xlsx") 
    Do While file <> "" 
     Set wb = Application.Workbooks.Open(file) 
     If Not IsEmpty(wb) Then 
      Application.Visible = False 
      userform1.Show 
     End If 
     wb.Close 
     file = Dir() 
    Loop 
End Sub 
+0

爵士,它显示的运行时间错误 - 91即是‘对象变量或与块变量未设置’并突出显示行”文件= DIR (mypath&“\”&“* .xlsx”)“ –

+0

我的不好,我忘了检查你是如何声明你的变量的!你应该声明'file as string',因为'Dir()'会给你一个字符串!尝试编辑! ;) – R3uK

+0

@shrees:Plz花一分钟去参观http://stackoverflow.com/tour(并接受答案,因为你是会员2个月,但还没有接受!)。我最后的评论/编辑应该工作得很好! ;) – R3uK