我需要能够在150个csv文件上运行一个宏,该文件双击工作表中的每个非空单元格。我之所以需要这样做,是因为除非我双击该单元格,否则我所包含的文件包含Excel无法识别的自定义日期格式。因为我有150个工作表,每个工作表都有成千上万的列和行,所以我需要从python注入一个宏,因为我使用的是python。为了注入宏,我使用以下代码,这些代码是我从另一篇文章(Use Python to Inject Macros into Spreadsheets)复制而来的;我做了一些修改以适合我的设置。 问题是,如果我在excel中运行VBA代码,它就可以工作,但是如果我从python注入它,宏将无法执行任何操作。我认为这与我将文件从dat转换为csv的方式有关。这是我使用的代码。
for j in range(len(dat_names)):
# to record elapsed runtime
archive_member_cycler_start = time.time()
archive_members_list.extract(dat_names[j],destination)
with open('%s.dat' % dat_names[j][:-4], 'r', encoding='ISO-8859-1') as input_file:
# remove | characters from the data
newLines = []
for line in input_file:
newLine = [x.strip() for x in line.split('|')]
# remove ^ characters from the data also; they are the last column
newLine = newLine[:-3]
newLines.append(newLine)
with open('%s.csv' % dat_names[j][:-4], 'w', newline='') as output_file:
file_writer = csv.writer(output_file)
try:
file_writer.writerows(newLines)
archive_member_cycler_end = time.time()
archive_member_cycler_run = archive_member_cycler_end-archive_member_cycler_start
a = '%s: %s.dat converted to csv (%.3f)' % (newpath[i], dat_names[j][:-4], archive_member_cycler_run)
print(a)
other.append(a)
# remove dat file because dont want it
os.remove('%s.dat' % dat_names[j][:-4])
except Exception as e:
print(e)
pfn = str(newpath[i]+': '+dat_names[j][:-4])
archive_member_cycler_end = time.time()
archive_member_cycler_run = archive_member_cycler_end-archive_member_cycler_start
a = '%s: %s.dat converted to csv WITH ERROR (%.3f)\n' % (newpath[i], dat_names[j][:-4], archive_member_cycler_run);
print(a)
other.append(a)
# compress the problematic dat file
zipper = zipfile.ZipFile('%s.zip' % dat_names[j][:-4], 'w')
zipper.write('%s.dat' % dat_names[j][:-4], compress_type=zipfile.ZIP_DEFLATED)
zipper.close()
# remove the dat file because dont want it
os.remove('%s.dat' % dat_names[j][:-4])
pass
关于如何使宏起作用的任何想法?
答案 0 :(得分:1)
我通常使用TextToColumns函数。
B列示例:
Columns("B:B").TextToColumns Destination:=Range("B1"), DataType:=xlDelimited, _
TextQualifier:=xlDoubleQuote, ConsecutiveDelimiter:=False, Tab:=True, _
Semicolon:=False, Comma:=False, Space:=False, Other:=False, FieldInfo _
:=Array(1, 1), TrailingMinusNumbers:=True