|
本帖最后由 huanger999 于 2014-4-13 21:57 编辑
- Sub getnew()
- Application.ScreenUpdating = False
- Dim mytable, myFirstRow As Range
- Dim strHuzhu As String
- Dim strZhuzhi As String
- 'For i = 3 To 10000
- 'If a Then Exit For
- 'Next
- '定义excel对象
- Dim AppExcel As Excel.Application, Wk As Excel.Workbook, Wksh As Excel.Worksheet
- '打开Excel文件
- With Application.FileDialog(msoFileDialogFilePicker)
- .AllowMultiSelect = False '单选择
- .Filters.Clear '清除文件过滤器
- .Filters.Add "Excel Files", "*.xls;*.xlw;*.xlsx"
- .Filters.Add "All Files", "*.*" '设置两个文件过滤器
- If .Show = -1 Then
- 'FileDialog 对象的 Show 方法显示对话框,并且返回 -1(如果您按 OK)和 0(如果您按 Cancel)。
- myfilepath = .SelectedItems(1)
- Else
- Exit Sub
- End If
- End With
- Set AppExcel = CreateObject("Excel.Application")
- Set Wk = AppExcel.Workbooks.Open(myfilepath)
- Set Wksh = Wk.sheets(1)
- For i = 3 To 1000 '暂时按照Excel文件有1000条数据,如果超过,就修改为数据条数
- If Wksh.Range("I" & i).Text = "" Then Exit For
- If Wksh.Range("I" & i).Text = "户主" Then
- '读取户主信息和住址信息
- strHuzhu = Wksh.Range("B" & i).Text
- strZhuzhi = Wksh.Range("J" & i).Text
- strAddress = Split(strZhuzhi, "@")
- '将模板表复制到最后
- ActiveDocument.Tables(1).Range.Copy
- Selection.EndKey Unit:=wdStory
- Selection.TypeParagraph
- Selection.PasteAndFormat (wdFormatOriginalFormatting)
- '替换表头信息,包括户主姓名和住址
- Set mytable = ActiveDocument.Tables(ActiveDocument.Tables.Count).Range
- mytable.Tables(1).Cell(1, 1).Range.Find.Execute findtext:="《户主姓名》", replacewith:=strHuzhu, Replace:=1
- mytable.Tables(1).Cell(1, 1).Range.Find.Execute findtext:="《乡镇》", replacewith:=strAddress(1), Replace:=1
- mytable.Tables(1).Cell(1, 1).Range.Find.Execute findtext:="《村名》", replacewith:=strAddress(2), Replace:=1
- mytable.Tables(1).Cell(1, 1).Range.Find.Execute findtext:="《村民小组》", replacewith:=strAddress(3), Replace:=1
- mytable.Tables(1).Cell(1, 1).Range.Find.Execute findtext:="《门牌》", replacewith:=Replace(strAddress(4), "号", ""), Replace:=1
- myRow = 3 '新的表格从第三行开始填写人口信息
- End If
- '如果某户人数超过7人,开始增加行,这样无论某户多少人口,最后总有一个空行
- If myRow > 7 Then
- mytable.Tables(1).Cell(myRow - 1, 2).Range.Select
- Selection.InsertRowsBelow 1
- End If
- '填写人口信息数据
- mytable.Tables(1).Cell(myRow, 2).Range = Wksh.Range("B" & i)
- mytable.Tables(1).Cell(myRow, 3).Range = Wksh.Range("D" & i)
- mytable.Tables(1).Cell(myRow, 4).Range = Wksh.Range("I" & i)
- mytable.Tables(1).Cell(myRow, 6).Range = Wksh.Range("E" & i)
- mytable.Tables(1).Cell(myRow, 8).Range = Wksh.Range("F" & i)
- mytable.Tables(1).Cell(myRow, 10).Range = strAddress(0)
- '行数加1
- myRow = myRow + 1
- Next
- '退出excel文件
- AppExcel.Quit
- Set Wksh = Nothing
- Set Wk = Nothing
- Set AppExcel = Nothing
- Application.ScreenUpdating = True
- End Sub
复制代码
|
|