2017-01-26 16 views
1

は値を取りません: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でカラムを見つけ、私はこのコラムでの操作のための変数制御2を使用しています。しかし、まずrngExchange2は値 "Isin"を取らず、第2にcontrol2変数は0のままです。それを助けてくれますか?

+0

あなたはループに入らないようだ言うから。 "Isin"の前の列にはすべて値がありますか? – Vityata

+2

Rangeオブジェクトの 'Find'メソッドを使わないのはなぜですか? VBAのセルごとにループするよりもはるかに簡単です。また、セルインデックスに 'Integer'を使用すると、オーバーフローの危険があります。代わりに 'Long'を使用してください。 –

+1

コードのどこかにカーソルを置き、F8キーを押して、コードの動作を確認しましたか? –

答えて

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 
0

.cells(2、intCounter2)を使用している場合、最初のパラメータは行を指定し、2番目のパラメータは変数です。私はあなた自身のシートに ブレークポイントでコードをテストしました。そして、 "Isin"を見つけることができるようです。

正しい場所にIsinがあることを確認し、Isinの大文字と小文字を区別して、大文字と小文字を区別してVBAコードに一致することを確認します。

うまくいけばうまくいくはずです。

関連する問題