vbamacrosembedded基于单元格的OLEobject

我想embedded一个OLEObject(文本文件)在Excel中,文件名是从一个特定的单元格派生。 我可以将其作为一个单独的动作来执行,但是现在正在试图使其在一个列中的所有单元格中循环工作,并在遇到空单元格时结束。 我似乎无法得到正确的语法来使If / Else循环工作:

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 

我认为你目前的做法的问题是,你只是分配值的pathvariables只有一次 – file = Range(i,1).Value & "-Live" & ".txt"之前,循环增加i

一个更好的方法需要更less的variables将使用for each循环使用Rangetypes的cellvariables,并依靠VBAfind最后一行使用,而不是硬编码200循环。

试试这种方法,让我们知道如果这工作。

 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