2016-09-06 129 views
1

當另一個用戶運行我的添加時,我得到下標超出範圍錯誤,但自己運行相同的代碼時沒有問題。設置工作簿值時會發生這種情況。文件名是通過獲取當前日期並存儲爲gendate來生成的。由此,文件名是基於用戶所做的文件路徑創建和保存的。在本例中,gv.Range(「b2」)。文本的值爲C:\ Users \ username \ Desktop \ ReportGeneration。因此,fp是C:\ Users \ dmulhausen \ Desktop \ ReportGeneration \ TSReports9_6_201615h5m32s.xlsx 這不會爲我生成錯誤,但會爲腳本的其他用戶生成錯誤。下標超出範圍錯誤9 vba

Dim ai As Workbook 'add in data ---Initialized in Report Setup 
Dim dwb As Workbook 'destination workbook ---Initialized in Report Setup 
Dim ss As Worksheet 'source sheet 
Dim ds As Worksheet 'destination sheet or writing sheet 
Dim rv As Worksheet 'reporting variables sheet ---Initialized in Report Setup 
Dim pv As Worksheet 'ts variables sheet ---Initialized in Report Setup 
Dim gv As Worksheet 'global ai variables ---Initialized in Report Setup 
Dim tempstr As String 
Dim fp As String 'file path ---Initialized in Report Setup 
Dim gendate As Date 
Dim reportscreated As Integer 
Dim initialized As Boolean 
Dim sheetnames(1 To 12) As String 

Sub reportsetup() 
    Set ai = Workbooks("TSReports add in.xlam") 
    Set rv = ai.Worksheets("ReportVars") 
    Set pv = ai.Worksheets("TS1_2Vars") 
    Set gv = ai.Worksheets("globalVars") 
    If (IsEmpty(gv.Range("b2").Value)) Then 
     MsgBox ("Please select a designated folder for reports") 
     With Application.FileDialog(msoFileDialogFolderPicker) 
      .AllowMultiSelect = False 
      .Show 
      If .SelectedItems.Count > 0 Then 
       gv.Range("b2").Value = .SelectedItems(1) 
      End If 
      ai.Save 
     End With 

    End If 
    initialized = True 
    gendate = Now() 
    tempstr = "TSReports" & Month(gendate) & "_" & Day(gendate) & "_" & Year(gendate) & Hour(gendate) & "h" & Minute(gendate) & "m" & Second(gendate) & "s" 
    fp = gv.Range("b2").Text & "\" & tempstr & ".xlsx" 
    Workbooks.Add 
    Application.DisplayAlerts = False 
    Application.AlertBeforeOverwriting = False 
    Application.DisplayAlerts = False 
    ActiveWorkbook.SaveAs Filename:=fp 
    Set dwb = Workbooks(tempstr) '*******Error occurs here******* 

回答

0

參見:Windows().Activate works on every computer except one

這應該可以解決這個問題。

tempstr = "TSReports" & Month(gendate) & "_" & Day(gendate) & "_" & _ 
      Year(gendate) & Hour(gendate) & "h" & Minute(gendate) & "m" & _ 
      Second(gendate) & "s" & ".xlsx" 

fp = gv.Range("b2").Text & "\" & tempstr 

Workbooks.Add 
Application.DisplayAlerts = False 
Application.AlertBeforeOverwriting = False 
Application.DisplayAlerts = False 
ActiveWorkbook.SaveAs Filename:=fp 
Set dwb = Workbooks(tempstr) 

但是這將是更穩健:

Set dwb = Workbooks.Add 
Application.DisplayAlerts = False 
Application.AlertBeforeOverwriting = False 
Application.DisplayAlerts = False 
dwb.SaveAs Filename:=fp