扫描具有2个变量的单元格(cells(i,j))

时间:2019-02-26 15:02:21

标签: excel vba

我的字符串'strings'不能从应该从单元格(corY,i)获取数据的行中获取任何数据。

这是我的代码:

Dim strings As String

corY = 2

For i = 5 To 20

strings = ActiveWorkbook.ActiveSheet.Range(Cells(corY, i)).Value

MsgBox (strings)


Next i

3 个答案:

答案 0 :(得分:3)

替换:

strings = ActiveWorkbook.ActiveSheet.Range(Cells(corY, i)).Value

具有:

strings = ActiveWorkbook.ActiveSheet.Cells(corY, i).Value

注释:

Cells()中的一个Range()无效。但是,以下是一些设置有效范围的示例:

Sub examples()
    Dim r As Range

    Set r = Workbooks("qwerty.xlsm").Worksheets("Junp").Range("A1:B15")
    Set r = Worksheets("Junp").Range("A1:B15")
    Set r = Range(Cells(1, 1), Cells(15, 2))
    Set r = Range("Junp!A1:B15")
End Sub

答案 1 :(得分:2)

问题是先使用“范围”,然后再使用“单元格”。这对我有用,在excel的“ B”列中有一个字符串。

 Sub test5()

 Dim strings As String
 Dim k As Integer

 k = 5
 i = 2

 corY = 2

 For i = 2 To k

 strings = ActiveWorkbook.ActiveSheet.Cells(i, corY).Value

 MsgBox (strings)


 Next i

 End Sub

答案 2 :(得分:0)

通过使用以下类似内容,您将获得实际显示范围的反馈:

Option Explicit
Sub ShowCells()
    Dim myString As String
    Dim myRange As Range
    'Dim iCt As Integer, corY As Integer
    Dim iCt As Long, corY As Long
    corY = 2
    For iCt = 5 To 20
        Set myRange = ActiveWorkbook.ActiveSheet.Cells(corY, iCt)
        myString = myRange.Value
        MsgBox (myRange.Address & ":" & myString)
    Next iCt
End Sub