如何使用vba在范围内使用变量

时间:2012-09-10 11:19:08

标签: excel vba excel-vba

您好我已经编写了使用vba生成图形的代码。一切正常,但问题是我想使用变量来选择特定的列 代码是:

Set x = Range("$CF$2", Range("$CF$2").End(xlDown))
Set y = Range("$CG$2", Range("$CG$2").End(xlDown))
Dim c As Chart
Set c = ActiveWorkbook.Charts.Add
Set c = c.Location(Where:=xlLocationAsObject, Name:=assume)
With c
.ChartType = xlXYScatterLines

' set other chart properties

With .Parent
.Top = Range("cl1").Top
.Left = Range("cl12").Left
.Name = "c"
End With
End With

Dim s As Series
Set s = c.SeriesCollection(1)
With s
.Values = y
 .XValues = x
' set other series properties

End With

我想首先使用变量COLs来排除它们

Set x = Range("$CF$2", Range("$CF$2").End(xlDown))
Set y = Range("$CG$2", Range("$CG$2").End(xlDown))

COLs是字符串

的变量

2 个答案:

答案 0 :(得分:0)

我不确定我理解,但如果你想要一个基于字符串的Range对象,为什么不试试这个:

Option Explicit

Sub TestRange()

    '***** Declare variables
    Dim oX As Range
    Dim sCOLs As String

    '***** Select column
    sCOLs = "A"


    '***** Set Range based on column from sCOLs
    Set oX = Range(sCOLs & "2", Range(sCOLs & "2").End(xlDown))

    '***** Do something with oX
    Debug.Print TypeName(oX)

    '***** Clean up
    Set oX = Nothing

End Sub

您也可以尝试将整个范围作为字符串,也许是一些更清晰的代码?

Dim sRange as String

sRange = "A2"

Set oX = Range(sRange, Range(sRange).End(xlDown))

答案 1 :(得分:0)

您还可以使用Inputbox让用户点击某个单元格。然后创建一个变量“UserRange”,其中包含您可以使用的单元格引用。

Sub test()

Dim UserRange As Range

Set UserRange = Application.InputBox(Prompt:="Please Select Range", Title:="Range Select", Type:=8)
UserRange.Value = "Test"

End Sub