我想在VBA中執行一個非常簡單的命令(將值賦給一個範圍),並得到一個錯誤「應用程序定義的或Web定義的錯誤」。經過一些故障排除後,我認爲它與我的工作表的定義有關。這裏是我的代碼:工作簿定義不正常
Sub CommandButton1_Click()
Dim arr() As String
Dim path As String
Dim filename As String
Dim w1 As Workbook
Dim w2 As Workbook
Set w1 = ThisWorkbook
Dim rng As Range
'w1.Worksheets(1).Range(Cells(1, 13), Cells(1, 22)) = 1 **#works perfectly, populates the given cells with 1's**
path = "C:\Users\Nenko\Desktop\"
filename = "D1.csv"
Workbooks.Open filename:=path & filename
ActiveSheet.Columns("A:B").EntireColumn.Delete
ActiveSheet.Columns("F:AQ").EntireColumn.Delete
ActiveSheet.Columns("G:G").EntireColumn.Delete
ActiveSheet.Columns("H:H").EntireColumn.Delete
ActiveSheet.Columns("I:J").EntireColumn.Delete
ActiveSheet.Columns("J:J").EntireColumn.Delete
ActiveSheet.Columns("K:P").EntireColumn.Delete
'Set w2 = Workbooks(path & filename) #subscript out of range
'Set w2 = ThisWorkbook **# application defined or web-defined error in Sheets.Add.Name=arr(a)**
Set w2 = ActiveWorkbook
'Set Range = w2.Worksheets(1).Range(Cells(1, 13), Cells(1, 22)) **# argument not optional**
'Range = 1
'w2.Worksheets(1).Range(Cells(1, 13), Cells(1, 22)) = 1 **#application defined or web-defined error**
EndRow = Sheets(1).Cells(Sheets(1).Rows.Count, "C").End(xlUp).Row
'w2.Worksheets(1).Cells(1, 11) = w2.Worksheets(1).Cells(1, 1).Value **#does nothing**
ActiveSheet.Range("A2:A65536").AdvancedFilter Action:=xlFilterCopy, CopyToRange:=ActiveSheet.Range("K:K"), Unique:=True
EndRow2 = Sheets(1).Cells(Sheets(1).Rows.Count, "K").End(xlUp).Row - 1
ReDim arr(EndRow2)
For a = 2 To EndRow2 + 1
arr(a - 1) = w2.Worksheets(1).Cells(a, 11).Value
Next
ActiveSheet.Columns("K:K").EntireColumn.Delete
For a = 1 To EndRow2
Sheets.Add.Name = arr(a)
c = 1
d = 1
For b = 1 To EndRow
If w2.Worksheets(a + 1).Cells(b, 1) = arr(a) Then
w2.Worksheets(1).Rows(c).EntireRow.Value = w2.Worksheets(a + 1).Rows(b).EntireRow.Value
c = c + 1
End If
'If w2.Worksheets(a + 1).Cells(b, 2) = arr(a) Then
'w2.Worksheets(1).Range(Cells(d, 13), Cells(d, 22)) = w2.Worksheets(a + 1).Range(Cells(b, 1), Cells(b, 10))
'd = d + 1
'End If **#this is what I tried to do initially and started getting the error**
Next
Next
End Sub
End Sub
#號後面我把我得到的錯誤時,將相應的行添加到代碼。
什麼代碼的作用是開放的第二工作簿時,從它的唯一片的第一列取唯一的值並創建爲每個唯一值的一個標籤中,包含對應於該值的行。它工作得很好,直到我試圖在第二張工作表w2中使用任何形式的範圍,它始終返回某種錯誤。
在故障排除期間,我發現命令 w1.Worksheets(1).Range(Cells(1, 13), Cells(1, 22)) = 1
用1填充工作簿w1中的相應單元。另一方面,命令 w2.Worksheets(1).Range(Cells(1, 13), Cells(1, 22)) = 1
返回「應用程序定義或Web定義的錯誤」
我不明白爲什麼它適用於一個工作簿,但不適用於其他。我曾嘗試用我在VBA中知道的每種方式來定義第二個工作簿,但每次都會遇到某種錯誤。
有沒有人有一個想法第二個工作簿有什麼問題?