我被告知我的问题在这里更合适,而不是在CodeReview
Global lineCount As Integer
Sub LoadWordFromExcel()
Const ONE As Integer = 1
Const FIRST_ROW As Integer = 2
Const PATH_TO_FOLDER As String = "C:\Users\<user>\Desktop\Macro folder\"
Const LAST_NAME As Integer = 3
Const CHOP_LEFT As Integer = 21
Const CHOP_RIGHT As Integer = 11
Dim r As Integer
Dim k As Integer
Dim c As Integer
Dim filePath As String
Dim file As String
Dim lastRow As Integer
Dim lastColumn As Integer
Dim sheet As Worksheet
Set sheet = ActiveSheet
'Finds last row and column with valid data
With ActiveSheet
lastRow = .Range("C" & .Rows.Count).End(xlUp).Row
lastColumn = ActiveSheet.Cells(ONE, Columns.Count).End(xlToLeft).Column
End With
For c = ONE To lastColumn
file = Dir$(PATH_TO_FOLDER & sheet.Cells(ONE, c).Value & ".docx")
If (Len(file) > 0) Then
filePath = PATH_TO_FOLDER & file
Dim entries As Scripting.Dictionary
Set entries = LoadWordToDictionary(filePath)
For r = FIRST_ROW To lastRow
For k = 1 To lineCount
If InStr(entries(k), sheet.Cells(r, LAST_NAME).Value) <> 0 Then
sheet.Cells(r, c).Value = Left(Right(entries(k), CHOP_LEFT), CHOP_RIGHT)
Exit For
Else
sheet.Cells(r, c).Value = ""
End If
Next
Next
End If
Next
MsgBox ("I'm Finished")
End Sub
'Loads data from word document and adds it to a dictionary
Private Function LoadWordToDictionary(file As String) As Scripting.Dictionary
Dim host As New Word.Application
Dim doc As Word.Document
Dim lines() As String
'loads data from Word doc into lines'
Set doc = host.Documents.Open(file)
lines = Split(doc.Content.Text, vbCr)
doc.Close
host.Quit
Dim output As New Scripting.Dictionary
Dim items() As String
Dim i As Integer
'Loads data from lines(array) to output(scripting.dictionary)
For i = 0 To UBound(lines)
Call output.Add(i + 1, lines(i))
Next i
lineCount = UBound(lines)
Set LoadWordToDictionary = output
End Function
在处理这个问题时,我提出了两个问题
当Word没有正常关闭时,它会弹出一个询问我是否要打开只读副本,本地副本或等待文件可用时收到通知的弹出窗口。我尝试使用.Open(file, ReadOnly)
,但它仍然给了我错误消息。有没有办法绕过这个来阻止程序停止并等待输入?
该计划也不是“智能”#34;并将无效数据放入单元格中。我一直在寻找mm-dd-yyyy,但是如果它不在字符串中,那么它就会放入名字的一部分。我怎么能阻止它输入任何不是mm-dd-yyyy格式但仍然使用字符串的数据?我尝试使用And / Or带来一些非常好笑的结果,所以我决定远离那个。