0

4 シートの Microsoft Excel ドキュメントがあります。各シートには、21 行と約 500 列があります。特定の値を持つこれらのシートのすべてのセルを埋める最近傍関数を作成しようとしています。

行データのレイアウト例:

  1. 25 41 54 54 XX 41 54 XX XX XX 54 14
  2. 23 88 33 XX 41 54 XX 87 48 65 77 14

すべてのデータを調べて、XX を最も近い行に置き換える必要があります。これは、ネストされたforループで各値 (各行の各列) を処理し、現在のセルが XX であるかどうかを確認することで実行できると考えています。その場合、XX 値を持たない最近傍を取得する必要があります。

4

2 に答える 2

0

以下のコードを試してください:

あなたのデータが下の画像のようなものであると仮定します。

ここに画像の説明を入力

コード:

Sub Sample()
    Dim rng As Range
    Set rng = Cells.Find("XX")

    Do Until rng Is Nothing
        rng.Value = rng.Offset(0, -1) 'Offset(0, -1) for left neighbour  , Offset(0, 1) for right
        Set rng = Cells.Find("XX")
    Loop
End Sub
于 2013-03-15T04:58:23.470 に答える
0

私はこれを試してみます...しかし、あなたは明確化の要求に応じなかったので、これはあなたが考えていたものと正確には異なるかもしれないことに注意してください. また、VBA を実行するマシンにアクセスせずにこれを行っているため、些細なバグが 1 つまたは 2 つある可能性があります。

Option Explicit
sub fillNN()
' we know there are five rows; number of columns is "approximate".
dim thisRow as Integer
dim s, c
dim r, rLast as range

for each s in WorkBook.WorkSheets
  s.Activate
  set r = Range("A1")

  For thisRow = 1 To 5
    set r = Range("A1").Offset(thisRow-1,0)
    set rLast = r.End(xlToRight) ' find the last cell in the row

    for each c in Range(r, rLast).cells
      if c.Value = "XX" Then
        c.Value = nearestNeighbor(c)
      end if
    next c
  Next thisRow

  ' the nearestNeighbor() function left the "XX" on the value
  ' now we have to strip it:
  For thisRow = 1 To 5
    set r = Range("A1").Offset(thisRow-1,0)
    set rLast = r.End(xlToRight) ' find the last cell in the row

    for each c in Range(r, rLast).cells
      if Left(c.Value, 2) = "XX" Then
        c.Value = MID(c.Value, 3, len(c.Value)-2)
      end if
    next c
  Next thisRow

Next s
End Sub

Function nearestNeighbor(c as Range)
' find the nearest "valid" cell:
' look to the left and to the right; if nothing found, extend the range by 1 and repeat
Dim rc, cc , dr, cs, s as Integer
Dim lastCol as Integer
Dim flag as Boolean
flag = true
s = 1 ' size of step

lastCol = c.End(xlToRight).column

' if c is the last cell, then the above will go to the end of the spreadsheet
' since we know there are "about 500" columns, we can catch that easily:
if lastCol > 1000 Then lastCol = c.column

' make sure there is always a return value:
nearestNeighbor = "XX"
While (flag)
  For dr = -1 To 1 Step 2
    cs = c.column + dr * s
    If Not(cs < 1 Or cs > lastCol) Then
      If Not c.offset(dr * s, 0).Value = "XX" Then
        flag = false
        ' keep the "XX" in front so it won't become a "valid nearest neighbor" on next pass
        nearestNeighbor = "XX" + c.offset(dr * s, 0).Value
        Exit For
      End If
    End If
  Next dr
  s = s + 1
  if s > lastCol Then flag = false
End While

End Function
于 2013-03-15T03:22:18.060 に答える