我使用下面的脚本将工作表导出为CSV:
Sub Button14_Click()
'
' export Macro
Dim LR As Long
LR = Range("A" & Rows.Count).End(xlUp).Row
Range("A2:M" & LR).SpecialCells(xlCellTypeConstants, 23).Select
Selection.Copy
Workbooks.Add
ActiveSheet.Paste
ActiveWorkbook.SaveAs Filename:= _
"C:\upload\19meat-kl.csv" _
, FileFormat:=xlCSV, CreateBackup:=False
Application.DisplayAlerts = False
ActiveWorkbook.Close
Application.DisplayAlerts = True
End Sub
我是VBA脚本的新手,实际上我从另一篇文章中得到了这段代码。
在大多数情况下,它可以满足我的需要,但如果我尝试使用公式,它会导出公式而不是结果。我需要更改哪些内容才能导出单元格内容?
答案 0 :(得分:1)
除了@Mat' sMug的评论之外,您还需要使用PasteSpecial xlValues
,而不仅仅是Paste
。
尝试下面的示例代码 - 它执行原始宏所做的事情,但使用了一些最佳做法:
使用Option Explicit
来防止错误定义的变量出现问题
设置对源数据和目标数据的引用,例如源工作表(wsSource
),源范围(rngToCopy
),目标工作簿(wbTarget
)和
目标工作表(wsTarget
) - 这比使用ActiveSheet
或Something.Select
等更好,这是不是最佳做法
copy 后立即执行粘贴以防止剪贴板持久性问题
代码:
Option Explicit
Sub SaveRangeDataAsValuesOnNewWorkbook()
' set-up your variables
Dim strFileToSave As String
Dim wsSource As Worksheet
Dim lngLastRow As Long
Dim wbTarget As Workbook
Dim wsTarget As Worksheet
Dim rngToCopy As Range
' where you want to save
strFileToSave = "C:\upload\19meat-kl.csv"
' get a worksheet reference
Set wsSource = ThisWorkbook.Worksheets("Sheet1") '<~~ set to your worksheet
' get last row in column A - you need to reference a worksheet to do this properly
lngLastRow = wsSource.Range("A" & wsSource.Rows.Count).End(xlUp).Row
' now - add a workbook and get its reference
Set wbTarget = Application.Workbooks.Add
' get the first worksheet in the new workbook
Set wsTarget = wbTarget.Worksheets(1)
' get a reference to your source range
Set rngToCopy = wsSource.Range("A2:M" & lngLastRow).SpecialCells(xlCellTypeConstants, 23)
' copy the source range
rngToCopy.Copy
' paste it to the target worksheet in the new workbook - you need to PasteSpecial to a Range
wsTarget.Range("A1").PasteSpecial xlValues
' save the new workbook
wbTarget.SaveAs Filename:=strFileToSave, FileFormat:=xlCSV, CreateBackup:=False
' close the new workbook
Application.DisplayAlerts = False
wbTarget.Close
Application.DisplayAlerts = True
End Sub