VBA变量不带值

时间:2017-01-26 13:23:51

标签: excel vba excel-vba

我有以下代码:

Dim intCounter As Integer
Dim intCounter2 As Integer
Dim rngExchange As Range
Dim rngExchange2 As Range
Dim control As Integer
Dim control2 As Integer

intCounter = 1
intCounter2 = 1

Do While Worksheets("Sheet2").Cells(2, intCounter2) <> ""
    If Worksheets("Sheet2").Cells(2, intCounter2).Value = "Isin" Then
        With Worksheets("Sheet2")
            Set rngExchange2 = .Range(.Cells(2, intCounter2), .Cells(2, intCounter2))
            control2 = intCounter2
        End With
    End If
    intCounter2 = intCounter2 + 1
Loop

代码找到标题为Isin的列,然后我将变量control2用于此列的操作。但是,首先rngExchange2不接受值“Isin”,其次control2变量保持为0.你能帮忙吗?

2 个答案:

答案 0 :(得分:0)

在使用.cells(2,intCounter2)的地方,第一个参数指定行,第二个参数是你的变量是列。我用你的代码测试过 在我自己的工作表中断点,它似乎能够找到“Isin”。

我会检查你是否有Isin在正确的位置,然后检查Isin的情况,以确保它与您在VBA代码中的内容相匹配,因为它区分大小写。

希望这对你有用。

答案 1 :(得分:0)

循环逻辑错误,在之前的问题中已得到纠正。

但我建议您使用更清晰的内容来查找特定文本的列,例如Range.Find方法:

Sub test_Anton()
Dim SearchString As String
Dim ConTrol2 As Integer
Dim wS As Worksheet
Dim cF As Range

SearchString = "Isin"

Set wS = ThisWorkbook.Sheets("Sheet2")

With wS
    .Activate
    With .Range("2:2")
        .Cells(1, 1).Activate
        'First, define properly the Find method
        Set cF = .Find(What:=SearchString, _
                    After:=ActiveCell, _
                    LookIn:=xlValues, _
                    LookAt:=xlPart, _
                    SearchOrder:=xlByRows, _
                    SearchDirection:=xlNext, _
                    MatchCase:=False, _
                    SearchFormat:=False)
        'If there is a result, stock the column
        If Not cF Is Nothing Then
            ConTrol2 = cF.Column
        Else
            MsgBox SearchString & " not found in " & wS.Name, vbOKOnly + vbCritical
        End If
    End With '.Range("2:2")
End With 'wS

MsgBox SearchString & " found in column " & ConTrol2 & " in sheet " & wS.Name, vbOKOnly + vbInformation
End Sub