Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.0k views
in Technique[技术] by (71.8m points)

excel - Embed OLEobject based on cell

I want to embed an OLEObject (text file) in Excel, with the filename being derived from a particular cell. I can do this as a one off action but am now trying to make it work in a loop through all the cells in a column, finishing when it comes across an empty cell.

I can't seem to get the right syntax to make the If/Else loop work:

Sub Insert_Text_File()

Dim ol As OLEObject
Dim path As String
Dim file As String
Dim filenameinvisible As String
Dim rangeA As Range
Dim rangeD As Range

path = ActiveWorkbook.Path
file = Range(i,1).Value & "-Live" & ".txt"
Set rangeA = Range("A" & i)
Set rangeD = Range("D" & i)

For i = 2 To 200
    If Range("A" & i) <> "" Then
        Set ol = Worksheets("Inventory").OLEObjects.Add (Filename:= path & "" & file, Link:=False, DisplayAsIcon:=True, Height:=10)

        ol.Top =Range("D" & i).top

        ol.left=Range("D" & i).left

    End If
    Next i
End Sub
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

I think the problem with your current approach is that your are assigning the value to the path variable only once - file = Range(i,1).Value & "-Live" & ".txt" before the loop increases i.

A better approach requiring less variables would be using a for each loop using a cell variable of Range type and relying on VBA to find the last row used rather than hard-coding 200 into the loop.

Try this approach and let us know if that has worked.

Sub Insert_Text_File()
Application.ScreenUpdating = False

    Dim cell As Range

    ' loop each cell in column A 
    For Each cell In Range("A2:A" & Range("A" & Rows.Count).End(xlUp).Row)
         ' make sure the cell is NOT empty before doing any work
         If Not IsEmpty(cell) Then

            ' create and insert a new OleObject based on the path
            Dim ol As OLEObject
            ' ActiveWorkbook.path & "" & cell & "-Live.txt" will make the filename
            Set ol = ActiveSheet.OLEObjects.Add( _
                                                Filename:=ActiveWorkbook.path & "" & cell & "-Live.txt", _
                                                Link:=False, _
                                                DisplayAsIcon:=True, _
                                                Height:=10)
            ' align the OleObject with Column D - (0 rows, 3 columns to the right from column A)
            With ol
                .Top = cell.Offset(0, 3).Top
                .Left = cell.Offset(0, 3).Left
            End With
        End If
    Next
Application.ScreenUpdating = True
End Sub

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share
...