这是我的代码,很简单!但我有一个错误 在这一行“wb.Sheets(”Sheet1“)。范围(单元格(3,j),单元格(10,j))。选择”
Private Sub CommandButton1_Click()
Dim fd As Office.FileDialog
Dim wb As Workbook
Dim ms As Workbook
Dim Path As String
Dim i As Integer
Dim j As Integer
Set ms = ThisWorkbook
Path = "D:\SYSTEM DATA\\EVT.xlsx"
Set wb = Workbooks.Open(Path)
wb.Activate
For i = 2 To 12 Step 1
If wb.Sheets(1).Cells(1, i).Value = "EVT006" Then
j = i
Exit For
End If
Next i
wb.Sheets("Sheet1").Range(Cells(3, j), Cells(10, j)).Select 'the error line
Selection.Copy
ms.Activate
With ms
Sheets(1).Cells(1, 1).PasteSpecial Paste:=xlPasteValues, Transpose:=True
Application.CutCopyMode = False
End With
wb.Close True
End Sub
我不知道为什么? 请帮忙
答案 0 :(得分:1)
一定要在范围内声明你的wb。
1.10.0
答案 1 :(得分:0)
in
wb.Sheets("Sheet1").Range(Cells(3, j), Cells(10, j)).Select
您wb.Sheets("Sheet1").Range(
引用了工作簿wb
的工作表“Sheet1”,而Cells(3, j)
和Cells(10, j)
引用了活动表活动工作簿,后者仍为wb
(由于wb.Activate
之前)而前者是工作表wb
正在打开(即活动上次保存时的表格),这不能保证是“Sheet1”
此外,您应该避免Activate
/ Select
/ ActiveXXX
/ Selection
模式并使用完全限定的范围参考
最后,在wb.Activate
之后您不需要任何Set wb = Workbooks.Open(Path)
语句,因为在任何工作簿打开时它都会成为 Active 一个
所以替换
wb.Sheets("Sheet1").Range(Cells(3, j), Cells(10, j)).Select 'the error line
Selection.Copy
ms.Activate
With ms
Sheets(1).Cells(1, 1).PasteSpecial Paste:=xlPasteValues, Transpose:=True
Application.CutCopyMode = False
End With
与
With Wb.Sheets("Sheet1")
.Range(.Cells(3, j), .Cells(10, j)).Copy
ms.Sheets(1).Cells(1, 1).PasteSpecial Paste:=xlPasteValues, Transpose:=True
Application.CutCopyMode = False
End With