VBA范围语法问题

时间:2015-06-18 21:11:27

标签: excel vba excel-vba

我试图创建一个最终用于concatinate函数的范围,但我有一些未知的错误。我附上了我的整个代码,但错误似乎是在“myRange'部分。代码的目标是将流程的步骤分成360分钟的班次,然后列出所需的所有部件和工具(见H列)。非常感谢帮助!

Private Sub CommandButton1_Click()

Dim duration As Integer, n As Long, i As Integer, x As Integer, m As Integer
Dim myRange As Range

n = 3
m = 3
duration = 0
x = 0

For i = 1 To 50

    duration = 0

    While duration < 360

        x = Worksheets("SR060-SR070").Cells(n, "F").Value
        duration = duration + x
        n = n + 1

    Wend

    myRange = Range(Worksheets("SR060-SR070").Cells(m, "H"), Worksheets("SR060-SR070").Cells(n, "H"))
    Worksheets("Shifts").Cells(1, i).Value = ConcatinateAllCellValuesInRange(myRange)
    m = n

Next i

End Sub

Function ConcatinateAllCellValuesInRange(sourceRange As Excel.Range) As String


    Dim finalValue As String

    Dim cell As Excel.Range

    For Each cell In sourceRange.Cells
    finalValue = finalValue + CStr(cell.Value)
    Next cell

    ConcatinateAllCellValuesInRange = finalValue
End Function

2 个答案:

答案 0 :(得分:1)

设置对象变量(例如范围,工作表或工作簿)以引用对象时,必须使用Set关键字。

Set myRange = Range(Worksheets("SR060-SR070").Cells(m, "H"), Worksheets("SR060-SR070").Cells(n, "H"))

这没关系,因为您正在设置范围的Value

Worksheets("Shifts").Cells(1, i).Value = ConcatinateAllCellValuesInRange(myRange)

ConcatinateAllCellValuesInRange函数中,For Each cell ... Next cell没问题。您应该使用&运算符来连接字符串。

答案 1 :(得分:1)

这是有问题的:

myRange = Range(Worksheets("SR060-SR070").Cells(m, "H"), _
                Worksheets("SR060-SR070").Cells(n, "H"))

这里的Range()方法没有工作表限定符,因此它将默认为活动工作表,如果它不是“SR060-SR070” - 将引发错误,因为您的Cells()调用正在引用另一张纸。

这会更好:

With Worksheets("SR060-SR070")
    Set myRange = .Range(.Cells(m, "H"), .Cells(n, "H"))
End With

(并根据ChipsLetten指出添加Set