Skip to content

Instantly share code, notes, and snippets.

@watermouth
Last active November 26, 2019 06:18
Show Gist options
  • Select an option

  • Save watermouth/326ba5221e299dd36c2f222f6635a6fd to your computer and use it in GitHub Desktop.

Select an option

Save watermouth/326ba5221e299dd36c2f222f6635a6fd to your computer and use it in GitHub Desktop.
VBA variant, Range, array
' 名前付き参照と配列の変換の実装例
' バリアント型の変数に Rangeプロパティの返り値を代入すると, 各セルの値を持った配列として受け取れる.
Sub execute()
Dim temp As Variant
' RangeFilePathsという名前の名前付き参照を用いてRangeオブジェクトへの参照を取得してtempに代入する.
' temp は 配列として扱える.
temp = Range("named_range_sample")
Dim i1 As Long
Dim i2 As Long
' 1次元方向つまり行方向の下限から上限でループ
' 下限は1となる. 配列一般の下限は0であることに注意すること.
For i1 = LBound(temp, 1) To UBound(temp, 1)
If temp(i1, 1) = "" Then
' VBAはcontinue文がないのでgotoする. cont: と書いてある行に跳ぶ.
GoTo cont
End If
Debug.Print temp(i1, 1), temp(i1, 2)
Next
cont:
End Sub
' シートの存在チェック
Function SheetExists(sheetName As String, Optional wb As Excel.Workbook)
Dim s As Excel.Worksheet
If wb Is Nothing Then Set wb = ThisWorkbook
On Error Resume Next
Set s = wb.Sheets(sheetName)
On Error GoTo 0
SheetExists = Not s Is Nothing
End Function
' 一度削除してシートを作り直す
Sub ClearSheet(sheetName As String)
Application.DisplayAlerts = False
With ThisWorkbook
If Not SheetExists(sheetName) Then
Exit Sub
End If
Sheets(sheetName).Delete
End With
Application.DisplayAlerts = True
End Sub
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment