• ベストアンサー

エクセルVBAでの画像ファイル名取得他

VBAについての質問です。 http://hp.vector.co.jp/authors/VA033788/kowaza.html#0158 上記をベースに、なんとかVBAを下記のように書き換えました。 Sub LoadPictures3() Dim Fnames As Variant Dim Fn As Variant Dim i As Integer Dim Pic As Picture Dim R As Range Dim R2 As Range Dim Pc As Integer Fnames = Application.GetOpenFilename("図(*.jpg;*.gif),*.jpg;*.gif", MultiSelect:=True) If TypeName(Fnames) = "Boolean" Then Exit Sub Application.ScreenUpdating = False '一枚目の貼付け位置 Set R = Range("B5") Set R2 = R.Offset(35) Pc = 0 For i = 1 To UBound(Fnames) Set Pic = ActiveSheet.Pictures.Insert(Fnames(i)) Select Case (i - 1) Mod 4 + 1 Case 1 Pc = Pc + 1 If Pc >= 2 Then ActiveSheet.HPageBreaks.Add R2 End If With R Pic.Left = .Left Pic.Top = .Top Pic.Width = 300 Pic.Height = 225 End With Case 2 With R.Offset(0, 6) '一枚目に対する二枚目の相対位置 Pic.Left = .Left Pic.Top = .Top Pic.Width = 300 Pic.Height = 225 End With Case 3 With R.Offset(18, 0) Pic.Left = .Left Pic.Top = .Top Pic.Width = 300 Pic.Height = 225 End With Case 4 With R.Offset(18, 6) Pic.Left = .Left Pic.Top = .Top Pic.Width = 300 Pic.Height = 225 End With '次ページの相対位置 Set R = R.Offset(39) End Select Next Application.ScreenUpdating = True End Sub ここで、画像の上の位置(B5のセル位置の画像の場合、B4)に 元々の画像ファイル名を取得し、表記させたいのですが 調べた所、multiselect:=Trueで複数ファイルを選択するときに 画像名が図1、図2に変わっているようで、どうしていいかわかりません。 後、画像を300×225の「変倍」画像にしたいのですが どのようにすれば可能でしょうか? 全くVBAの知識がなく、上のURLを参考に、単語を調べつつ書き換えている状態で、変数やらなんやらの指定・書き方等わかりません。 どなたかご教授願います。

質問者が選んだベストアンサー

  • ベストアンサー
  • lul
  • ベストアンサー率41% (10/24)
回答No.3

縦横比を保持しないという設定に関しては 以下の部分に1行付け加えれば大丈夫です。 前回の修正とあわせて2行の追加ですね。 With R Pic.ShapeRange.LockAspectRatio = msoFalse '←ここを追加 Pic.Left = .Left Pic.Top = .Top Pic.Width = 300 Pic.Height = 225 Pic.Name = FSO.GetBaseName(Fnames(i)) '←ここを追加 End With これでどうでしょう?

yn2008
質問者

お礼

レスありがとうございます。 返信が遅くなりましてすみません。 色々ありがとうございます、理想通りに上手くいきました! 他、ファイル名の配置の方も無事解決できました。 これで、仕事がスムーズに進みます! 色々お世話になりました。 本当にありがとうございます!!!

その他の回答 (2)

  • pkh4989
  • ベストアンサー率62% (162/260)
回答No.2

正確ではないけど、参考にしてください。 Sub LoadPictures3()   Dim Fnames As Variant   Dim Fn   As Variant   Dim i    As Integer   Dim Pic   As Picture   Dim R    As Range   Dim R2   As Range   Dim Pc   As Integer   Dim wH   As Integer   Dim wW   As Integer   '   wH = 1   '←高さの倍率を設定 (小数点、マイナス等は出来ません)   wW = 2   '←幅の倍率を設定   Fnames = Application.GetOpenFilename("図(*.jpg;*.gif),*.jpg;*.gif", MultiSelect:=True)   If TypeName(Fnames) = "Boolean" Then Exit Sub      Application.ScreenUpdating = False      '一枚目の貼付け位置   Set R = Range("B5")   Set R2 = R.Offset(35 * wH)   Pc = 0      For i = 1 To UBound(Fnames)     Set Pic = ActiveSheet.Pictures.Insert(Fnames(i))     nm = Get_Name(Fnames(i))    '←ファイル名称取得     Select Case (i - 1) Mod 4 + 1       Case 1         Pc = Pc + 1         If Pc >= 2 Then           ActiveSheet.HPageBreaks.Add R2         End If         With R           Pic.Left = .Left           Pic.Top = .Top           Pic.Width = 300 * wW           Pic.Height = 225 * wH         End With       Case 2         With R.Offset(0, 6 * wW) '一枚目に対する二枚目の相対位置           Pic.Left = .Left           Pic.Top = .Top           Pic.Width = 300 * wW           Pic.Height = 225 * wH         End With       Case 3         With R.Offset(18 * wH, 0)           Pic.Left = .Left           Pic.Top = .Top           Pic.Width = 300 * wW           Pic.Height = 225 * wH         End With       Case 4         With R.Offset(18 * wH, 6 * wW)           Pic.Left = .Left           Pic.Top = .Top           Pic.Width = 300 * wW           Pic.Height = 225 * wH         End With         '次ページの相対位置         Set R = R.Offset(39 * wH)     End Select     ActiveSheet.Pictures(i).Name = nm    '←ファイル名称設定   Next   Application.ScreenUpdating = True End Sub 'ファイル名称取得 Function Get_Name(wNm As Variant) As String   Dim wI   As Integer   Dim wSt   As String   Dim ExitFlg As Boolean   wSt = wNm   Do While ExitFlg = False     wI = InStr(wSt, "\")     If wI = 0 Then       ExitFlg = True     Else       wSt = Mid(wSt, wI + 1)     End If   Loop   Get_Name = wSt End Function

yn2008
質問者

お礼

レスありがとうございます。 返信が遅くなりましてすみません。 このやり方だと、縦横比が一律になってしまいますよね。 複数の、色々なサイズの画像を強制的に同じサイズにしたかったんです。 説明の仕方が下手ですみません。 ファイル名取得については、このやり方だと場所の情報になるんですね。 色々なことができるのだなぁ、と勉強になりました。 今回は、lulさんの方法で解決しましたが、ありがとうございます!!

  • lul
  • ベストアンサー率41% (10/24)
回答No.1

名前に関してはプログラム始まってすぐの所で Dim FSO Set FSO = CreateObject("Scripting.FileSystemObject") を宣言しておいて 以下の部分に1行付け加えれば大丈夫です。 With R Pic.Left = .Left Pic.Top = .Top Pic.Width = 300 Pic.Height = 225 Pic.Name = FSO.GetBaseName(Fnames(i)) '←ここを追加 End With Excel2000で試してみましたが、サイズに関してはちゃんと出来ているぽいですよ。 ピクセルとcmは違うので気をつけて下さいね。

yn2008
質問者

お礼

早々にありがとうございます! 試した所、無事名前を書き換えることができました!! (まだ、上手くセルに配置できていませんが、 もう少し試行錯誤してみます) 画像サイズについては、説明不足で申し訳ありません、 縦横比が元画像と同じまま配置されてしまうので、 これを強制的に300×225にしたいのです。 (例えば、縦の画像も変形させて、横に配置したいということです) 検索はしてみたのですが、近い物がみつからなくて…。。。

関連するQ&A

  • エクセル マクロ 画像についての質問です。

    エクセル マクロについての質問です。 下記のコードでセルに画像を合わせて貼り付け、表を作成しています。 が、このコードだと画像の保存先を移動させると画像が表示されなくなり、分類でフィルターをかけるとバラバラの違う画像が表示されてしまったりして困っています・・・。 どなたか良いご意見を頂ければと思い、投稿しました。よろしくお願いします! Sub PictFit() Dim PicFile As String Dim Pic As Picture PicFile = Application.GetOpenFilename() '画像のパスを取得 If PicFile = "False" Then Exit Sub Set Pic = ActiveSheet.Pictures.Insert(PicFile) '画像を貼り付ける With Pic .Height = ActiveCell.MergeArea.Height '画像の高さ .Top = ActiveCell.Top '画像の上位置を変更 .Left = ActiveCell.Left + (ActiveCell.MergeArea.Width - .Width) / 2 '画像の横位置を変更(セル幅中央に画像中央) End With End Sub

  • Excel VBA チェックボックスの判断

    下記のようなマクロでチェックボックスを作成したのですが、その作成したチェックボックスをクリックしたときに、ある処理を実行させるようにするにはどうすればいいのでしょうか? よろしくお願いします。 Dim Max as Long Dim Cell as Range Dim Check as CheckBox ・ ・ ・ For i = 0 To Max   With Cell.Offset(i)   Set Check = ActiveSheet.CheckBoxes.Add_     (Left:=.Left,Top:=.Top, Width:=.Width, Height:=.Height)   End With   With Check   .LinkedCell = Cell.Address   .Caption = ""   .Value = False   End With Next

  • VBAで特定の文字が含まれている画像ファイル

    下記コードで画像の貼り付けを行っていますが 現在は適当な順番で貼り付けが行われます。 Declare Function SetCurrentDirectory Lib "kernel32" Alias _ "SetCurrentDirectoryA" (ByVal CurrentDir As String) As Long Sub ShapeLoadtest() Dim Fname As Variant, fe As Variant Dim Fn As Variant, Pic As Shape Dim pno As Long Dim myFileName As String Dim strFileName As String Range("B4").Select SetCurrentDirectory "C:\Users\yuya\Desktop\画像\" Fname = Application.GetOpenFilename _ (",*", MultiSelect:=True) If Not IsArray(Fname) Then MsgBox "取り消されました。", vbInformation Exit Sub End If Application.ScreenUpdating = False pno = 0 For Each Fn In Fname 'この次へ追加すべき行 Selection.Offset(-1, 0) = Mid(Fn, InStrRev(Fn, "\") + 1, Len(Fn) - InStrRev(Fn, "\")) ActiveCell.Select Set Pic = ActiveSheet.Shapes.AddPicture(Filename:=Fn, _ LinkToFile:=False, _ SaveWithDocument:=True, _ Left:=0, Top:=0, Width:=0, Height:=0) With Pic .ScaleWidth 1, msoTrue .ScaleHeight 1, msoTrue .Top = ActiveCell.Top ' 位置:アクティブセルの上側に重ねる .Left = ActiveCell.Left ' 位置:アクティブセルの左側に重ねる .Placement = xlMove ' 移動するがサイズ変更しない End With If ActiveCell.Column = 2 Then ActiveCell.Offset(, 8).Select ElseIf ActiveCell.Column = 10 Then ActiveCell.Offset(, 8).Select ElseIf ActiveCell.Column = 18 Then ActiveCell.Offset(32, -16).Select End If Set Pic = Nothing pno = pno + 1 Next Application.ScreenUpdating = True Range("A1").Select MsgBox pno & "枚の画像を挿入しました", vbInformation End Sub これを画像ファイル名に【あいう】という文字が混じっていたら If ActiveCell.Column = 2 Then ActiveCell.Offset(, 8).Select のセルに 【123】という数字が混じっていたら ElseIf ActiveCell.Column = 10 Then ActiveCell.Offset(, 8).Select のセルに貼り付けという具合にしたいです。 よろしくお願いします。

  • エクセル2007のVBAの困りごと

    教えてください。 画像挿入時にエクセルのセルの大きさに合わせるマクロを使っているのですが、エクセル2000、2003では問題なく動くのですが、2007だと、うまくVBAが動かず、画像が縮小・拡大されません。 わかるかた教えてください。 コード  Dim c As Range, cm As Range Application.ScreenUpdating = False For Each c In Selection Set cm = c.MergeArea If c.Address = cm.Item(1).Address Then If Application.Dialogs(xlDialogInsertPicture).Show = False    Then Exit Sub  With Selection .Left = cm.Left .Top = cm.Top .Height = cm.Height .Width = cm.Width End With End If Next Set cm = Nothing

  • エクセル2010 挿入画像の圧縮 VBA

    お世話になります。 エクセル2010を使用しています。写真帳を作成しダブルクリックすれば写真が挿入されるようVBAにて作成しましたが、写真の解像度が高いので挿入するたびに画像が圧縮するようにVBAを組みたいのですが、どなたかご教示ください。 具体的には一同挿入した画像を一度コピーし、再度貼り付ける・・・という動作かなと考えているのですが、マクロの記憶では記録されず・・・困っております。 現在の写真帳の構文は Private Sub Worksheet_BeforeDoubleClick(ByVal Target As Excel.Range, Cancel As Boolean) Dim myF As Variant Dim mySp As Object Dim myAD1 As String Dim myAD2 As String Dim myHH As Double Dim myWW As Double Dim myHH2 As Double Dim myWW2 As Double '挿入のセルを指定 If Application.Intersect(Target, Range("d6,d23,d40")) Is Nothing Then Exit Sub Cancel = True Application.ScreenUpdating = False End If '写真挿入 Next myPic = Application.GetOpenFilename("画像ファイル,*.jpg;*.jpeg;*.gif;*.tif") If myPic = False Then MsgBox "画像を選択してください" Exit Sub End If Set myRange = Target 'このセル範囲に収まるように画像を縮小する Application.ScreenUpdating = False With ActiveSheet.Shapes.AddPicture(myPic, False, True, myRange.Left, myRange.Top, myRange.Width, myRange.Height) rX = 0.85 rY = 1 If rX > rY Then .Height = .Height * rY Else .Width = .Width * rX End If .Left = .Left + (myRange.Width - .Width) / 2 '写真を横方向の中央に配置 .Top = .Top + (myRange.Height - .Height) / 2 '写真を縦方向に中央に配置 .ZOrder msoSendToBack '最背面へ移動 End With Application.ScreenUpdating = True Cancel = True End Sub 上記に.CUT などを書き足せばよいのか・・・ →エラーばかりで動かなったので。。  こちらに質問することにしました。 どうぞ、よろしくお願いします。

  • (VBA)スピンボタンの大量コピー(相対参照)

    お世話になります。質問させていただきます。 表題件ですが、EXCELにて 「A列にコントロールツールの"スピンボタン"をリンクセルを相対参照にして縦に大量にコピー(さらに増減値をデフォルトの1から10に変更)」したいと考えています。 以下に記載したVBAコードは、こちらと同様のQ&Aサイトにて見つけてきた「A列にコントロールツールの"チェックボックス"をリンクセルを相対参照にして縦に大量にコピー」するコードです。 先ずは参考までにご確認ください。 ----------------------------------------------------------------- Sub Checkbox連続作成() Dim myChk As Object Dim i As Long Dim Sakuseisuu As Long Dim StartCell As Range '--------↓ここを変更--------- Sakuseisuu = 20 'チェックボックスの作成数 Set StartCell = Range("A1") 'スタートする位置 '--------↑ここを変更--------- For i = 0 To Sakuseisuu - 1 With StartCell.Offset(i) Set myChk = ActiveSheet _ .OLEObjects.Add(classtype:="Forms.CheckBox.1", _ Link:=False, DisplayAsIcon:=False, _ Left:=.Left, Top:=.Top, _ Width:=.Width, Height:=.Height) End With With myChk .LinkedCell = StartCell.Offset(i, 1).Address .Object.Caption = "" .Object.Value = False End With Next End Sub ------------------------------------------------------------------ 上記コードを参考に、「A列にコントロールツールの"スピンボタン"をリンクセルを相対参照にして縦に大量にコピー」すべく、コードを以下のように短絡的に書き換えてみましたが、エラーとなってしまいます。 ------------------------------------------------------------------ Sub SpinButton連続作成() Dim myspin As Object Dim i As Long Dim Sakuseisuu As Long Dim StartCell As Range '--------↓ここを変更--------- Sakuseisuu = 20 'チェックボックスの作成数 Set StartCell = Range("A1") 'スタートする位置 '--------↑ここを変更--------- For i = 0 To Sakuseisuu - 1 With StartCell.Offset(i) Set myspin = ActiveSheet _ .OLEObjects.Add(classtype:="Forms.SpinButton1.", _ Link:=False, DisplayAsIcon:=False, _ Left:=.Left, Top:=.Top, _ Width:=.Width, Height:=.Height) End With With myspin .LinkedCell = StartCell.Offset(i).Address .Object.Caption = "" .Object.Value = False End With Next End Sub ------------------------------------------------------------------ お詳しいかたがおられましたら、是非ともアドバイスを頂戴したく存じます。 さらにわがままを述べると、増減値をデフォルトの1から10に変更したく考えております。 何卒よろしくお願い申し上げます。

  • EXCELのVBAで画像ファイルを呼び出し

    EXCELのVBAでセルに入力されているファイル名の画像ファイルを呼び出して、 トリミング、縮小→一旦切り取り、メタファイルで貼り付け→セルの真ん中に配置ということを行いたいです。 このようなVBAを組みましたが、bw = .Width でエラーが起こってしまいます。 一旦切り取りして貼り付けするコードを加えたらエラーになりました。 どのようにしたらきちんと希望の形ではりつけることができるでしょうか? よろしくお願いします。 Sub photocalltest() 'セルの値を取得して画像を貼り付け ' ' Dim i As Long For i = 2 To 5 ActiveSheet.Pictures.Insert ("C:\Documents and Settings\temp\" & Cells(7, i).Value & ".jpg") With ActiveSheet.Shapes(ActiveSheet.Shapes.Count) 'トリミング .PictureFormat.CropBottom = 95 .PictureFormat.CropRight = 57.78 .PictureFormat.CropLeft = 59.28 .PictureFormat.CropTop = 100 '縮小 .Height = 197.25 .Width = 162# .Cut 'Cells(7, i).Select ActiveSheet.PasteSpecial Format:="図 (拡張メタファイル)" '貼り付け位置指定 aw = Cells(7, i).Width bw = .Width //ここでオブジェクトが必要ですエラー x = (aw - bw) / 2 .Left = Cells(7, i).Left + x ah = Cells(7, i).Height bh = .Height y = (ah - bh) / 2 .Top = Cells(7, i).Top + y End With Next i End Sub

  • エクセルのマクロで画像を貼り付け 

    画像をエクセルに貼り付ける作業を行っています。 マクロを使いファイル内の画像(約30枚程度)を1列づつスペースを空け 右方向に4枚 1行スペースを空け 3行目の左に戻り その位置よりまた1列づつスペースを空け右方向に4枚・・・・・ これを繰り返しファイル内の画像をすべて 貼り付けたいのですがうまく動作が出来ません。 何卒ご教授の程よろしくお願いします。 ※マクロ Sub EggFunc_pasteDirImage() ' 変数定義 Dim fileName As String Dim targetCol As Integer Dim targetRow As Integer Dim targetCell As Range Dim shell, myPath Dim pos As Integer Dim extention As String Dim isImage As Boolean ' 選択セルを取得 targetCol = ActiveCell.Column targetRow = ActiveCell.Row ' フォルダ選択画面を表示 Set shell = CreateObject("Shell.Application") Set myPath = shell.BrowseForFolder(&O0, "フォルダを選んでください", &H1 + &H10, "C:\Users\0602116.MS\Desktop\") Set shell = Nothing ' フォルダを選択したら... If Not myPath Is Nothing Then fileName = Dir(myPath.Items.Item.Path + "\") Do While fileName <> "" ' ファイル拡張子の判別 isImage = True pos = InStrRev(fileName, ".") If pos > 0 Then Select Case LCase(Mid(fileName, pos + 1)) Case "jpeg" Case "jpg" Case "gif" Case Else isImage = False End Select Else isImage = False End If ' 拡張子が画像であれば If isImage = True Then ' 貼り付け先を選択 Cells(targetRow, targetCol).Select Set targetCell = ActiveCell ' 画像読込み ActiveSheet.Pictures.Insert(myPath.Items.Item.Path + "\" + fileName).Select ' 画像が大きい場合、画像サイズをセル幅に合わせる If Selection.Width > targetCell.Width Or Selection.Height > targetCell.Height Then If Selection.Width / targetCell.Width > Selection.Height / targetCell.Height Then Selection.Height = Selection.Height * (targetCell.Width / Selection.Width) Selection.Width = targetCell.Width Else Selection.Width = Selection.Width * (targetCell.Height / Selection.Height) Selection.Height = targetCell.Height End If End If ' 表示位置をセル中央に移動 Selection.Top = targetCell.Top + (targetCell.Height - Selection.Height) / 2 Selection.Left = targetCell.Left + (targetCell.Width - Selection.Width) / 2 ' 貼り付け先行を+1 targetCol = targetCol + 2 End If fileName = Dir() Loop MsgBox "画像の読込みが終了しました" End If End Sub

  • エクセルに画像挿入

    以前の投稿で下記のようなVBAを拝見しました。 実行するとA列に画像ファイル名、B列に画像が縦に配置されます。 これを横に配置するにはどうすればいいのでしょうか? 初心者なので質問不足かもしれませんがよろしくお願いします。 Sub PictAdd() Dim pict As Shape, r As Range With Application.FileSearch  .NewSearch  .LookIn = ThisWorkbook.Path  .SearchSubFolders = False  .Filename = "*.jpg"  If .Execute() > 0 Then   For i = 1 To .FoundFiles.Count    Set r = ActiveSheet.Range("B" & i)    Set pict = ActiveSheet.Shapes.AddPicture _       (.FoundFiles(i), msoTrue, msoFalse, _        r.Left, r.Top, r.Width, r.Height)       pict.OnAction = "PictClick"       r.Offset(0, -1).Value = Dir(.FoundFiles(i))   Next i  End If End With  Columns(1).EntireColumn.AutoFit End Sub

  • 画像をエクセルに貼り付けるマクロ

    画像をエクセルに貼り付けるマクロ 複数の画像をエクセルに貼り付ける機会が多く、下記のマクロを利用しています。これは他人が作ったものでその人が今はいないため修正の仕方がわかりません。 これだとヨコに2個の画像で縦方向に画像が貼り付けられます。これをヨコに3個の画像で 縦方向に画像を貼り付けるようにしたいのですが、方法がわかりません。 お詳しい方どうかよろしくお願いします。 <現在> 1  2 3  4 5  6 <やりたいこと> 1  2  3 4  5  6 7  8  9 Sub Insertpic() Dim strFilter As String Dim Filenames As Variant Dim pic As picture Dim sc As Range Dim i As Long Dim j As Long Dim k As Long '「ファイルを開く」ダイアログでファイル名を取得 strFilter = "画像ファイル(*.jpg;*.jpeg;*.gif;*.bmp;*.png),*.jpg;*.jpeg;*.gif;*.bmp;*.png" Filenames = Application.GetOpenFilename( _ FileFilter:=strFilter, _ Title:="画像の挿入(複数画像が選択できます)", _ MultiSelect:=True) If Not IsArray(Filenames) Then Exit Sub ' 貼り付け開始セルを選択 'ActicveCellRange("C5").Select ' マクロ実行中の画面描写を停止 Application.ScreenUpdating = False ' 順番に画像を挿入 For i = LBound(Filenames) To UBound(Filenames) Set pic = ActiveSheet.Pictures.Insert(Filenames(i)) '画像の大きさ指定 With pic.ShapeRange .Height = 120# .Width = 175# .Rotation = 0# End With ' 次の貼り付け先を選択 Select Case i Mod 2 Case 1 '奇数回目 ActiveCell.Offset(, 4).Select Case 0 '偶数回目 ActiveCell.Offset(11, -4).Select End Select Set pic = Nothing Next i ' 終了 Application.ScreenUpdating = True MsgBox i - 1 & "枚の画像を挿入しました", vbInformation End Sub

専門家に質問してみよう