我不知道为什么我可以将范围值存储在工作表变量的range属性中,而不是存储在范围变量中。每次我尝试运行此代码时都会收到错误91:
Dim ws As Worksheet, rng As Range
Set ws = Worksheets.Add
ws.name = "Potato"
rng = ws.Range("A1:K1")
rng.PasteSpecial
我能够通过将最后两行替换为:
来成功运行程序 ws.Range("A1:K1").PasteSpecial
这很有效,即使它使我的代码的其他部分混乱。但我无法理解使用范围变量的问题是什么。
我希望任何人都可以提供任何澄清。
答案 0 :(得分:1)
您必须将Set
与对象变量一起使用:
Set rng = ws.Range("A1:K1")
答案 1 :(得分:0)
以下是添加的代码,如果您已经有一张名为" Potato"
的工作表,那么将确保不会出现错误确保Sheet(" Potato")的代码不存在。
Sub Button1_Click()
Dim ws As Worksheet, rng As Range, cRng As Range
Dim worksh As Integer
Dim worksheetexists As Boolean
Dim s As String
s = "Potato"
Set cRng = ActiveSheet.Range("A1:K1")
worksh = Application.Sheets.Count
worksheetexists = False
For x = 1 To worksh
If Worksheets(x).Name = s Then
worksheetexists = True
MsgBox s & ", already Exists"
Exit For
End If
Next x
If worksheetexists = False Then
Set ws = Worksheets.Add()
ws.Name = s
Set rng = ws.Range("A1:K1")
cRng.Copy
rng.PasteSpecial Paste:=xlPasteAll
Application.CutCopyMode = 0
End If
End Sub