我想在Excel中嵌入一个OLEObject(文本文件),文件名源自特定单元格。我可以做到这一点作为一次性动作,但我现在正试图让它循环通过一列中的所有单元格,当它遇到一个空单元格时结束。 我似乎无法使用正确的语法来使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
答案 0 :(得分:2)
我认为您当前的方法存在的问题是,您只需在path
变量file = Range(i,1).Value & "-Live" & ".txt"
之前将值分配给i
变量 - for each
。
需要更少变量的更好方法是使用cell
循环使用Range
类型的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
变量,并依靠VBA查找最后使用的行而不是硬编码200进入循环。
尝试这种方法,让我们知道是否有效。
{{1}}