Excel VBA范围变量串联

时间:2018-07-10 18:22:47

标签: excel vba excel-vba excel-formula word-vba

我具有以下Excel VBA代码块。 现在,我必须将它们放入循环并对其进行参数化。

Countruz2 = 2
 Countruz3 = Countruz2 + 13

Range("A2:A15").PasteSpecial (xlPasteValues)

下面是我尝试过的-3个变体均失败:属性错误的无效使用。

'    Range ("A" & Countruz2 & ":" & "A" & Countruz3)                                    ' Invalid Use of Property

'    Range ("A" & Countruz2 & ":A" & Countruz3)                                         ' Invalid Use of Property

'    Range ("A" & Countruz2 & ":A" & Countruz2 + 13)                                    ' Invalid Use of Property

我们如何在Excel VBA的Range函数中处理此类串联和参数化?

感谢所有的帮助。

编辑:

将其连接起来后使其正常工作-

X =“ A”&Countruz2&“:”&“ A”&(Countruz2 + 13) 调试打印X 范围(X).PasteSpecial(xlPasteValues)

还有其他优雅/简单的方法吗?

2 个答案:

答案 0 :(得分:1)

尝试一下

SELECT t1.id AS lev1, t2.id AS lev2, t3.id AS lev3, t4.id AS lev4, t5.id AS lev5, t6.id AS lev6, t7.id AS lev7, t8.id AS lev8, t9.id AS lev9, t10.id AS lev10, (SELECT COUNT(*) FROM tbl_master_fund where receiver_id = 1) as entry_count FROM tbl_users AS t1 LEFT JOIN tbl_users AS t2 ON t2.sponsorid = t1.id LEFT JOIN tbl_users AS t3 ON t3.sponsorid = t2.id LEFT JOIN tbl_users AS t4 ON t4.sponsorid = t3.id LEFT JOIN tbl_users AS t5 ON t5.sponsorid = t4.id LEFT JOIN tbl_users AS t6 ON t6.sponsorid = t5.id LEFT JOIN tbl_users AS t7 ON t7.sponsorid = t6.id LEFT JOIN tbl_users AS t8 ON t8.sponsorid = t7.id LEFT JOIN tbl_users AS t9 ON t9.sponsorid = t8.id LEFT JOIN tbl_users AS t10 ON t10.sponsorid = t9.id LEFT JOIN tbl_users AS t11 ON t11.sponsorid = t10.id WHERE t1.sponsorid = 1 HAVING entry_count > 0 

答案 1 :(得分:0)

您确定要复制范围吗?否则,将xlPasteValues添加到.pastespecial

的末尾时会出现错误
Sub main()
    Dim Countruz2 As Integer
        Countruz2 = 2

    Dim ws As Worksheet
        Set ws = ActiveSheet

    ws.Range("C1:D100").Copy

    With ws
        .Range("A1" & Countruz2).PasteSpecial xlPasteValues
    End With

    Application.CutCopyMode = False

    Set ws = Nothing
End Sub

有时使用范围名称,我将创建一个字符串,该字符串将给出我的范围:

Sub main()
    Dim Countruz2 As Integer
        Countruz2 = 2

    Dim ws As Worksheet
        Set ws = ActiveSheet

    ws.Range("C1:D100").Copy

    Dim rngName As String
        rngName = "A1"

    With ws
        .Range(rngName).PasteSpecial (xlPasteValues)
    End With

    Application.CutCopyMode = False

    Set ws = Nothing
End Sub