3
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

Excelで必要な列のみ抽出するスピル関数を作ってみた

Last updated at Posted at 2022-10-07

はじめに

Filter関数を使っていて、便利だなと思ったのですが、必要な列だけを抽出することができず、いろいろ調べてみましたができないようなので、自作のスピル関数を作ってみました。

前提

スピルが利用できるバージョンのExcelであること

スピルとは

数式を入力したセルから結果があふれて隣接したセルにも出力される機能です。

スピルを利用した関数には以下のようなものがあります。

  • SORT関数
  • SORTBY関数
  • FILTER関数
  • UNIQUE関数
  • RANDARRAY関数
  • SEQUENCE関数
  • XLOOKUP関数

仕様

関数名: extractCols
第1引数:配列(列を絞り込みたい範囲を表すもの)
第2引数以降:第1引数で指定した配列から抽出したいカラム番号。1~の数値を指定

実装

実装コードは以下の通り「WorksheetFunction.Transpose」を使って、行列を入れ替え
そして必要な行のみに絞り、最後に再度行列を入れ替えて、応答するというもの

Option Explicit

Function extractCols(ByVal vArray As Variant, ParamArray cols() As Variant) As Variant
    
    Dim dummyArray As Variant
    Dim resutlArray() As Variant
    Dim count As String
    Dim col As Variant
    
    ' 配列の行列を入れ替える
    dummyArray = WorksheetFunction.Transpose(vArray)
    
    count = 0
    ' 行列入れ替えたので、指定した行のみを、新しい配列に追加
    For Each col In cols
        ReDim Preserve resutlArray(count)
        resutlArray(count) = WorksheetFunction.Index(dummyArray, CInt(col))
        count = count + 1
    Next
    
    ' 配列の行列を入れ替え、結果に設定
    extractCols = WorksheetFunction.Transpose(resutlArray)

End Function

結果

想定している通りの結果となりました。

image.png

Filter関数の結果を第1引数に入れることもできます。ある表から
一定の条件で抽出したのち列を絞りたいというときに使うことができます。

おわりに

スピルを調べる中で、独自関数を作る場合の可変長パラメータなど
今までやったことなかった要素もあって、なかなか勉強になりました。

3
2
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?