为什么Range(Cells(),Cells())
使用的第二种格式不起作用?
Sub start()
Dim ws As Worksheet
Dim wb As Workbook
Dim cond_rng As Range
Set ws = Application.Workbooks("ndata.xlsm").Worksheet("conditionsSheet")
' This works and selects one cell
Set cond_rng = ws.Cells(4, 1)
cond_rng.Select
'this works as expected
Set cond_rng = ws.Range("A1:B10")
cond_rng.Select
'this fails with error 1004
Set cond_rng = ws.Range(Cells(1, 1), Cells(4, 4))
cond_rng.Select
答案 0 :(得分:3)
好的,这很有效:
'this works
Set cond_rng = ws.Range(ws.Cells(1, 1), ws.Cells(4, 4))
cond_rng.Select
或
With Sheets("conditionsSheet")
.Range(.Cells(1, 1), .Cells(4, 4)).Select
End With
.Cells
很重要,因为它不适用于单元格。
答案 1 :(得分:0)
我测试了一个简单的子,如下所示,它的工作原理。我认为您的错误来自“工作表”之后的“s”缺失。
设置ws = Application.Workbooks(“ndata.xlsm”)。工作表(“conditionsSheet”) 应该是...工作表......
sub TEST()
Dim ws As Worksheet
Dim cond_rng As Range
Set ws = Worksheets("sheet1")
Set cond_rng = ws.Range(Cells(1, 1), Cells(5, 4))
cond_rng.Value = 5
End Sub
答案 2 :(得分:0)
我认为这是令人困惑的范围选择。如果您尝试从非活动工作表中选择范围,通常会出现错误。
如果您尝试从另一个工作表中获取该范围的值或需要将信息添加到该范围,则不必选择它。例如:下面的代码将循环遍历每个工作表并复制A1:D4(不包括PasteSheet)并将其粘贴到PasteSheet中。 对于此示例,请确保您有一个名为“PasteSheet”的工作表
Sub SheetLoop()
Dim ws As Worksheet
Dim sh As Worksheet
Set ws = Sheets("PasteSheet")
For Each sh In Sheets
If sh.Name <> ws.Name Then
With sh
.Range(.Cells(1, 1), .Cells(4, 4)).Copy ws.Cells(Rows.Count, "A").End(xlUp).Offset(1, 0)
End With
End If
Next sh
End Sub
您可以从工作簿中的任何工作表运行此代码,因为您不必选择任何内容。
因此,如果例如Sheet2 A1 = 2,则sheet1(A1:D4)颜色为红色,否则为蓝色。
Sub Button2_Click()
Dim ws As Worksheet, x
Dim sh As Worksheet, rng As Range, Crng As Range
Set ws = Sheets("Sheet1")
Set sh = Sheets("Sheet2")
Set rng = sh.Range("A1")
Set Crng = ws.Range(ws.Cells(1, 1), ws.Cells(4, 4))
x = IIf(rng = 2, vbRed, vbBlue)
Crng.Interior.Color = x
End Sub