0

私には(私にとって)少しトリッキーな仕事があります。指定された列の最後のセルの値を(ヘッダーに従って)見つけるマクロを作成したいと思います。たとえば、「test」という列の最後の値が検索されます。

4

2 に答える 2

1

あなたが試みなかったので、またはあなたが試みてそれを理解することができなかったので、それはあなたにとってトリッキーですか?最初にコードを提供しておけば、何をしているのか、そしてそれを機能させるためにどのように役立つのかを確認できるので、いつでも便利です。

とにかく、これがあなたが求めることをするために私がまとめたものです。で検索することを前提としていSheet 1ます。で、このコードVisual Basic Editor (VBE)を開いSheet1て貼り付けます。その後、通常のマクロのように使用できます(必要に応じて、ヘッダー行の値と検索文字列を変更してください)。

コード

Public Sub FindValueInColumn()

    Dim headerRow As Integer
    Dim totalColumnsInHeaderRow As Integer
    Dim searchColumn As Integer
    Dim lastRowInSearchColumn As Integer
    Dim columnSearchString As String

    headerRow = 1   'change this to correct header row
    totalColumnsInHeaderRow = Cells(headerRow, Columns.Count).End(xlToLeft).Column
    columnSearchString = "Test" 'change to the text to search
    searchColumn = 0

    'for every column that has a value in it in the header row
    Dim currentColumn As Integer
    For currentColumn = 1 To totalColumnsInHeaderRow
        'if that value equals what we're looking for (in this case, "Test")
        If StrComp(Cells(headerRow, currentColumn).Value, columnSearchString, vbTextCompare) = 0 Then
            'save the column that contains the value, then exit the loop
            searchColumn = currentColumn
            Exit For
        End If
    Next

    'if the column of interest exists in the header row
    If searchColumn > 0 Then
        'Set F2 equal to the last value in that column
        lastRowInSearchColumn = Cells(Rows.Count, searchColumn).End(xlUp).Row
        Range("F2").Value = Cells(lastRowInSearchColumn, searchColumn).Value
    End If

End Sub

ここに画像の説明を入力してください

ここに画像の説明を入力してください

于 2013-03-12T15:50:50.227 に答える
1

さまざまなコーディングスタイルを見るのが大好きです。どうやら、この猫の皮を剥ぐ方法は複数あります。

Sub Last_Cell_In_Column()
   Dim sh As Worksheet
   Dim col As Long

   Set sh = ThisWorkbook.ActiveSheet
   col = 0
   col = sh.Rows(1).Find("test").Column
   If col > 0 Then
      MsgBox (sh.Cells(sh.Rows.Count, col).End(xlUp).Value)
   End If
End Sub
于 2013-03-12T16:13:09.503 に答える