以下代码在突出显示的行中给出了下标范围错误。不确定原因..请帮助
Private Sub CommandButton1_Click()
Dim New_Book As String
Dim Address As String
Dim Source As String
Dim Version As String
Dim NWkbook As Workbook
Dim WkSheet1, WkSheet2, WkSheet3 As Worksheet
Application.SheetsInNewWorkbook = 1
'WkSheet2.Name = "Scenarios"
'WkSheet3.Name = "Considerations"
Version = "1"
Source = ActiveWorkbook.FullName
'MsgBox (Source)
Address = Application.ActiveWorkbook.Path
New_Book = Address + "\" & Worksheets("Test Scenarios").Range("A2") + "_SIT_Scenarios_V" + Version + ".0"
'MsgBox (Dir(New_Book + "*"))
'thesentence = InputBox("Type the filename with full extension", "Raw Data File")
If Len(Dir(New_Book + "*")) = 0 Then
Else
Do
Version = Version + 1
New_Book = Address + "\" & Worksheets("Test Scenarios").Range("A2") + "_SIT_Scenarios_V" + Version + ".0"
Loop Until Dir(New_Book + "*") = ""
End If
'MsgBox (New_Book)
New_Book = New_Book + ".xlsx"
Set NWkbook = Workbooks.Add
NWkbook.Worksheets("Sheet1").Name = "Considerations"
Set WkSheet2 = Sheets.Add
WkSheet2.Name = "Scenarios"
Set WkSheet1 = Sheets.Add
WkSheet1.Name = "Estimation"
NWkbook.SaveAs New_Book
'MsgBox (Source)
***Workbooks(Source).Activate***
'Workbooks(Source).Worksheets("Test Scenarios").Select
'Workbooks(NWkbook).Worksheets("Scenarios").Range("A1").Paste
End Sub
答案 0 :(得分:1)
尝试将行Source = ActiveWorkbook.FullName
更改为Source = ActiveWorkbook.Name
- 它将修复错误。
但是使用以下结构:
Source = ActiveWorkbook.Name
'your code
Workbooks(Source).Activate
不是编程的好方法。尝试将其更改为以下结构(避免在代码中使用Select
和Activate
语句。Here是一个非常好的解释,为什么你不应该使用它们以及你应该使用什么代替):
Dim thisWb As Workbook
Set thisWb = ThisWorkbook
'your code
thisWb.Sheets("Sheet1").Range("A1")="newValue"
最后一件事:当你像这样delcare变量
Dim WkSheet1, WkSheet2, WkSheet3 As Worksheet
只有WkSheet3
是Worksheet
类型的对象,WkSheet1
和WkSheet2
是Variant
。
您应该使用以下声明:
Dim WkSheet1 As Worksheet, WkSheet2 As Worksheet, WkSheet3 As Worksheet