我是VBA的新手所以请耐心等待。我想在每个活动行的最后一个单元格中追加文件名。因此,例如,行/列A1,B1,C1和D1被填充,我想将文件名添加到单元格E1。文件名应仅附加到活动行。我玩过不同的迭代而没有太多运气。下面是我到目前为止,逻辑显然不正确。任何帮助,将不胜感激。谢谢!
Sub InsertFilename()
Dim Count1 As Long
Count1 = 1
Dim ColumnE As String
ColumnE = "E1"
While Cells(Count1, 1) <> ""
Range(ColumnE).Select
ActiveCell.FormulaR1C1 = _
"=MID(CELL(""filename""),SEARCH(""["",CELL(""filename""))+1, SEARCH(""]"",CELL(""filename""))-SEARCH(""["",CELL(""filename""))-1)"
ColumnE = Range(ActiveCell, ActiveCell.Offset(1, 0)).Select
Count1 = Count1 + 1
Wend
End Sub
答案 0 :(得分:0)
此代码从第一行迭代到最后一行,它通过模拟工作表边缘的CTRL + LEFT来查找每行中的最后一列。
不假设所有行都具有相同的列数
Dim LastRow As Long
Dim LastColumn As Long
Sub InsertFileName()
Application.ScreenUpdating = False
Dim i as Long
LastRow = ActiveSheet.Cells(ActiveSheet.Rows.Count, "A").End(xlUp).Row
For i=1 To LastRow
LastColumn = ActiveSheet.Cells(i, ActiveSheet.Columns.Count).End(xlToLeft).Column
ActiveSheet.Cells(i,LastColumn+1)="=CELL(""filename"")"
Next i
Application.ScreenUpdating = True
End Sub
答案 1 :(得分:0)
一个简单的解决方案。添加要追加的fileName
的值以及数据的起始行stRow
。
Sub InsertFilename()
Dim stRow As Long, endRow As Long, endCol As Long, c As Long
Dim fileName As String
fileName = "C:\Data\somefile.xlsx"
stRow = 1
With ActiveSheet
endRow = .Cells(Rows.Count, 1).End(xlUp).Row
For c = stRow To endRow
endCol = .Cells(c, Columns.Count).End(xlToLeft).Column
If endCol > 1 Then
.Cells(c, endCol + 1) = fileName
End If
Next
End With
End Sub
答案 2 :(得分:0)
此解决方案使用Counta测试活动,并使用每个活动行的最后一列来使用activeworkbook的全名。
Dim lngLastRow As Long
Dim lngLastCol As Long
Dim lngCounter As Long
lngLastRow = Cells.Find(What:="*", SearchOrder:=xlByRows, SearchDirection:=xlPrevious).Row
lngLastCol = Cells.Find(What:="*", SearchOrder:=xlByColumns, SearchDirection:=xlPrevious).Column
For lngCounter = 1 To lngLastRow
If WorksheetFunction.CountA(Range(Cells(lngCounter, 1), Cells(lngCounter, lngLastCol))) > 0 Then
Cells(lngCounter, lngLastCol + 1).End(xlToLeft).Offset(0, 1).Value = ActiveWorkbook.FullName
End If
Next lngCounter