• 締切済み

VBAでカンマ区切り数値をハイフンでまとめたい

以前、下記の質問をさせていただきました。 エクセルでハイフンで示した数値の範囲を別々の数値へ http://okwave.jp/qa/q8192454.html これの逆をやりたいと思い、下記のように改造してみました。 例:1,2,3,5,7,8,9,10,12→1-3,5,7-10,12 しかし#VALUE!になってしまいます。 どこがおかしいのか色々試してみましたが、分かりません。 どなたかご教授頂けると幸いです。 Function hSample(sData As String) As String sOne = Split(sData, ",") For i = 0 To UBound(sOne) For j = 1 To 255 If Int(sOne(i)) + j <> Int(sOne(i + j)) Then ElseIf j > 1 Then sOne(i) = sOne(i) & "-" & sOne(i) + j Exit For End If Next j hSample = hSample & "," & sOne(i) Next i hSample = Right(hSample, Len(hSample) - 1) End Function

みんなの回答

  • 30246kiku
  • ベストアンサー率73% (370/504)
回答No.3

連続が3つ以上の時に "-" を使うという事で 例) 1,2,4,5,6 → 1,2,4-6 Public Function hSample(sSrc As String) As String   Dim v As Variant   Dim i As Long   Dim sS As String, sE As String, sSep As String   hSample = sSrc   v = Split(sSrc, ",")   If (UBound(v) < 0) Then Exit Function   sS = v(0)   sE = sS   sSep = ","   For i = 1 To UBound(v)     If (v(i) - v(i - 1) = 1) Then       sS = sE & sSep & v(i)       sSep = "-"     Else       sS = sS & "," & v(i)       sE = sS       sSep = ","     End If   Next   hSample = sS End Function 蛇足)いろいろな書き方を見るのも良いのかな、ということで Public Function fSample(sSrc As String) As String   Dim v As Variant   Dim i As Long, j As Long, k As Long   Dim sS As String   fSample = sSrc   v = Split(sSrc, ",")   If (UBound(v) < 0) Then Exit Function   For i = 0 To UBound(v)     k = InStr(v(i), "-")     If (k > 0) Then       sS = ""       For j = Left(v(i), k - 1) To Mid(v(i), k + 1)         sS = sS & "," & j       Next       v(i) = Mid(sS, 2)     End If   Next   fSample = Join(v, ",") End Function ※ 双方とも暗黙的な型変換を使ってみました。  (型変換は明示的にした方が良さそうですけど)

  • watabe007
  • ベストアンサー率62% (476/760)
回答No.2

こんばんは >例:1,2,3,5,7,8,9,10,12→1-3,5,7-10,12 こんなことかな? Function hSample(sData As String) As String   Dim sOne As Variant, strEnd As String, i As Long   sOne = Split(sData, ",")   hSample = sOne(0)   strEnd = hSample   For i = 1 To UBound(sOne)     If Int(sOne(i - 1)) + 1 <> Int(sOne(i)) Then       hSample = hSample & "," & Int(sOne(i))       strEnd = hSample     Else       hSample = strEnd & "-" & Int(sOne(i))     End If   Next End Function

回答No.1

まず、hSampleが初期化されていません。 次に For j=1 To 255 のところですが、 i=UBound(sOne)のときにsOne(i+1)の値は・・・・ありませんよね? もう一つ、 For i = 0 To UBound(sOne) とやると 結果は、 1-3,2-3,3,・・・・ となってしまう気がします。 もう少し、工夫が必要のようですね