我对此还比较陌生,但我能够编写出第一批代码,这些代码实际上完成了一些有用的任务。代码的目的是打开一个电子表格,提取由名称给出的行的值,并将其复制到主电子表格中,以此类推。
不幸的是,当代码所在的单元格中的间距发生变化时,代码并不特别健壮。是否有办法将“营运费用总额”改为"*营运费用总额*“,目的是间距并不重要,而只涉及单元格中的字。
If Cells(i, 1).Value = " Total Operating Expenses" Then
Range("B" & i, "M" & i).Copy
TargetWb.Sheets("T-12 Drop").Range("E" & 9 + (k - 1) * 9).PasteSpecial Paste:=xlPasteValues 整个守则列示如下:
Sub ImportData()
Dim filePath As String
Dim SourceWb As Workbook
Dim TargetWb As Workbook
Dim Cell As Range
Dim i As Integer
Dim k As Integer
Dim Lastrow As Long
Dim Lastrow2 As Long
'SourceWb - Workbook were data is copied from
'TargetWb - Workbook were data is copied to and links are stored
Application.ScreenUpdating = False
Set TargetWb = Application.Workbooks("APC Refi Tracker.xlsm")
Lastrow = Range("E100").End(xlUp).Row - 6
For k = 1 To Lastrow
filePath = TargetWb.Sheets("Import").Range("E" & 6 + k).Value
Set SourceWb = Workbooks.Open(filePath)
On Error Resume Next
Lastrow2 = Range("A500").End(xlUp).Row - 2
For i = 1 To Lastrow2
If Cells(i, 1).Value = " Total Rental Income" Then
Range("B" & i, "M" & i).Copy
TargetWb.Sheets("T-12 Drop").Range("E" & 4 + (k - 1) * 9).PasteSpecial Paste:=xlPasteValues
End If
If Cells(i, 1).Value = " Total Other Income" Then
Range("B" & i, "M" & i).Copy
TargetWb.Sheets("T-12 Drop").Range("E" & 5 + (k - 1) * 9).PasteSpecial Paste:=xlPasteValues
End If
If Cells(i, 1).Value = " Total Operating Expenses" Then
Range("B" & i, "M" & i).Copy
TargetWb.Sheets("T-12 Drop").Range("E" & 9 + (k - 1) * 9).PasteSpecial Paste:=xlPasteValues
End If
Next
SourceWb.Close
Next
Application.ScreenUpdating = True
Worksheets("Import").Activate
MsgBox "All done!"
End Sub发布于 2020-09-04 21:25:48
您可以对单元格的值使用Application.Trim (这只是WorksheetFunction.Trim的后期绑定版本):
If Application.Trim(Cells(i, 1).Value) = "Total Rental Income" Then对于其他的提取值也是如此。
附带说明:
On Error Resume Next只是在隐藏潜在的错误。最好的做法是避免使用that.Application.Trim,而只是Trim或Trim$的行为略有不同。Application.Trim将删除单词之间的空格,而Trim或Trim$将只删除整个字符串上的前导或尾随空格。您是否使用其中一种取决于首选项和数据。Debug.Print Application.Trim(" Total Rental Income ") '<~ returns "Total Rental Income"
Debug.Print Trim$(" Total Rental Income ") '<~ returns "Total Rental Income"https://stackoverflow.com/questions/63747986
复制相似问题