2
5

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 5 years have passed since last update.

vba macroサンプル集 (①セル参照範囲を文字列化 ②CSVファイルから指定セルへコピー)

Last updated at Posted at 2017-10-24

目的

2種類のサンプルコードを示す。

  • Worksheet関数で参照セル範囲を文字列化する方法が面倒だったので、ユーザ定義関数を作成した。
  • CSVファイルを読み込み、指定セルへコピーするマクロの雛形を作成した。

用途/特長

  1. RangeToText Function
    セル参照範囲を文字列化するユーザ定義関数。文字列にシート名を付与するので、別シートを参照する場合にも対応できる。

  2. CopyFromCSV Subroutine
    CSVファイルを読み込み、指定したセルに書き出すマクロ。第1引数には相対パス(..\sample.csv など)を使用できる。

Attribute VB_Name = "utils"
Option Explicit


Function RangeToText(rng As Range) As String
    Dim sheetName As String
    sheetName = rng.Parent.Name
    RangeToText = "'" & sheetName & "'!" & rng.Address
End Function

Sub CopyFromCSV(path As String, rng As Range)

Dim absPath As String
Dim lineText As String
Dim splitText As Variant, result As Variant
Dim fp As Integer, i As Integer, j As Integer


absPath = ThisWorkbook.path & "\" & path
fp = FreeFile
result = rng   ' result is One origin.
i = 0
j = 0

Open absPath For Input As fp
Do Until EOF(1)
    i = i + 1
    Line Input #fp, lineText
    splitText = Split(lineText, ",") ' splitText is ZERO origin.
    
    For j = 0 To UBound(splitText)
        result(i, j + 1) = splitText(j)
    Next j
Loop
Close #fp

rng = result
End Sub

2
5
0

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
2
5

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?